Python 3.x 使用bs4从列表或html解析器获取参数

Python 3.x 使用bs4从列表或html解析器获取参数,python-3.x,beautifulsoup,google-search,Python 3.x,Beautifulsoup,Google Search,我试图通过输入拼写错误的单词来获得建议的谷歌单词: 下面是我的代码:输入:Johnny walker路lbl输出:Johnny walker红色标签 import requests import pandas as pd from bs4 import BeautifulSoup from pprint import pprint key = "Johnny walker rd lbl" query = "https://www.google.com/search?q=" + key r = r

我试图通过输入拼写错误的单词来获得建议的谷歌单词:

下面是我的代码:输入:
Johnny walker路lbl
输出:
Johnny walker红色标签

import requests
import pandas as pd
from bs4 import BeautifulSoup
from pprint import pprint
key = "Johnny walker rd lbl"
query = "https://www.google.com/search?q=" + key
r = requests.get(query)
html_doc = r.text
soup = BeautifulSoup(html_doc, 'html.parser')
#for s in soup.find_all(id="rhs_block"):
 #   pprint(s.text)
find=soup.find_all('script',attrs={'type':'text/javascript'})
mylist = []
for x in find:
    mylist.append(str(x.string))
print(mylist)
输出:

['None', "(function(){var eventid='QO7rW5TtM5OYvQT516NY';google.kEI = 
eventid;})();", 'google.ac&&google.ac.c({"agen":true,"cgen":true,
"client":"heirloom-serp","dh":true,"dhqt":true,"ds":"","ffql":"en","fl":true,"host":"google.com","isbh":28,"jsonp":true,
"msgs":{"cibl":"Clear Search","dym":"Did you mean:","lcky":"I\\u0026#39;m Feeling Lucky","lml":"Learn more",
"oskt":"Input tools","psrc":"This search was removed from your \\u003Ca href=\\"/history\\"\\u003EWeb History\\u003C/a\\u003E","psrl":"Remove",
"sbit":"Search by image","srch":"Google Search"},"ovr":{},"pq":"Johnny walker red label","refpd":true,"rfs":[],"sbpl":24,"sbpr":24,"scd":10,"sce":5,"stok":"7UqfdDr4nbKtZNfvytsBW8kPB9E","uhde":false})']
如何从可用输出列表中仅获取“pq”标签。请帮助。

使用正则表达式

import re

....
html_doc = r.text
output = re.search(r'"pq":"([^"]+)', html_doc).group(1)

非常好,谢谢,我不认为我们可以在html解析中实现正则表达式。第一次与bs4合作。感谢@EWINKI正在尝试在for循环下生成结果并将其保存为列表,但是无法做到这一点,每个字母都作为列表项出现。这有什么原因吗?你是在做
myList=[]吗。。。对于myList.append(output)
?算了吧,我刚刚发现我在for循环中定义了列表:p需要休息一下,我想,这很有效。:)