在谷歌搜索之后,我需要解析与结果的链接。当我试图查看页面和Ctrl + U的代码时,我找不到包含链接的元素,这是我想要的。但是,当我看到带有Ctrl + Shift + I的元素代码时,我可以看到应该解析哪些元素来获得链接。我用密码
url = 'https://www.google.ru/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=' + str(query)
html = requests.get(url).content
soup = BeautifulSoup(html, 'html.parser')
links = soup.findAll('cite')但是它返回空列表,因为这里没有这些元素。我认为返回html-code的requests.get(url).content不是满的,所以我不能得到这个元素。我试着使用google.search,但它返回错误,it isn't used now.是任何方式获得链接的搜索在谷歌?
发布于 2017-02-02 10:40:12
尝试:
url = 'https://www.google.ru/search?q=' + str(query)
html = requests.get(url)
soup = BeautifulSoup(html.text, 'lxml')
links = soup.findAll('cite')
print([link.text for link in links])有关安装lxml,请参见http://lxml.de/installation.html
*注意:我选择lxml而不是html.parser的原因是,有时我在html.parser上得到的结果不完全,我不知道为什么
发布于 2017-02-02 10:22:35
USe:
url = 'https://www.google.ru/search?q=name&rct=' + str(query)
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
links = soup.findAll('cite')发布于 2021-10-21 10:26:20
为了获得您在浏览器中看到的实际响应,您需要发送额外的标头,更具体地说,发送user-agent (除了发送附加查询参数之外),当机器人或浏览器发送假的user-agent字符串以宣布自己为不同的客户端时,它需要充当“真正的”用户访问。
这就是为什么您得到了一个空的输出,因为您收到了一个不同的HTML,具有不同的元素(CSS选择器,ID,等等)。
你可以在我写的关于如何减少网络抓取时被屏蔽的可能性的博客文章中读到更多关于它的内容。
Pass user-agent
headers = {
'User-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582'
}
requests.get('URL', headers=headers)在线IDE中的代码和示例
from bs4 import BeautifulSoup
import requests, lxml
headers = {
'User-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582'
}
params = {
'q': 'minecraft', # query
'gl': 'us', # country to search from
'hl': 'en', # language
}
html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')
for result in soup.select('.tF2Cxc'):
link = result.select_one('.yuRUbf a')['href']
print(link, sep='\n')
---------
'''
https://www.minecraft.net/en-us/
https://classic.minecraft.net/
https://play.google.com/store/apps/details?id=com.mojang.minecraftpe&hl=en_US&gl=US
https://en.wikipedia.org/wiki/Minecraft
'''或者,您也可以通过使用来自Google有机API的SerpApi来实现相同的目标。这是一个有免费计划的付费API。
不同之处在于,您不需要从头开始创建它,并且在某些东西崩溃时维护它。
合并守则:
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "minecraft",
"hl": "en",
"gl": "us",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results["organic_results"]:
print(result['link'])
-------
'''
https://www.minecraft.net/en-us/
https://classic.minecraft.net/
https://play.google.com/store/apps/details?id=com.mojang.minecraftpe&hl=en_US&gl=US
https://en.wikipedia.org/wiki/Minecraft
'''免责声明,我为SerpApi工作。
https://stackoverflow.com/questions/41997368
复制相似问题