如何使用BeautifulSoup在Python中解析Google搜索结果
问题内容:
我正在尝试解析Google搜索结果的首页。具体来说,就是标题和提供的小摘要。这是我到目前为止的内容:
from urllib.request import urlretrieve
import urllib.parse
from urllib.parse import urlencode, urlparse, parse_qs
import webbrowser
from bs4 import BeautifulSoup
import requests
address = 'https://google.com/#q='
# Default Google search address start
file = open( "OCR.txt", "rt" )
# Open text document that contains the question
word = file.read()
file.close()
myList = [item for item in word.split('\n')]
newString = ' '.join(myList)
# The question is on multiple lines so this joins them together with proper spacing
print(newString)
qstr = urllib.parse.quote_plus(newString)
# Encode the string
newWord = address + qstr
# Combine the base and the encoded query
print(newWord)
source = requests.get(newWord)
soup = BeautifulSoup(source.text, 'lxml')
我现在停留的部分是沿着HTML路径解析我想要的特定数据。到目前为止,我尝试过的所有操作都抛出一个错误,说它没有属性,或者仅返回了[[]]。
我是Python和BeautifulSoup的新手,所以我不确定如何到达所需位置的语法。我发现这些是页面中的单个搜索结果:
我们非常感谢您提供任何关于解析每个搜索结果的标题和摘要的内容的帮助。
谢谢!
问题答案:
您的网址对我不起作用。但是有了https://google.com/search?q=
结果。
import urllib
from bs4 import BeautifulSoup
import requests
import webbrowser
text = 'hello world'
text = urllib.parse.quote_plus(text)
url = 'https://google.com/search?q=' + text
response = requests.get(url)
#with open('output.html', 'wb') as f:
# f.write(response.content)
#webbrowser.open('output.html')
soup = BeautifulSoup(response.text, 'lxml')
for g in soup.find_all(class_='g'):
print(g.text)
print('-----')
阅读美丽汤文档