如何在Python中使用BeautifulSoup解析google搜索结果

2024-09-28 17:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解析谷歌搜索结果的第一页。具体来说,标题和提供的小摘要。以下是我目前掌握的情况:

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://ibb.co/jfRakR

任何关于添加什么来解析每个搜索结果的标题和摘要的帮助都将不胜感激。

谢谢你!


Tags: thetextfromhttpsimport标题parseaddress
1条回答
网友
1楼 · 发布于 2024-09-28 17:30:56

你的网址对我不起作用。但有了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('-----')

阅读Beautiful Soup Documentation

相关问题 更多 >