Python请求未能提供整个响应

2024-03-29 05:34:12 发布

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

我目前正在学习网络报废。今天我试着去废纸谷歌网站搜索。当我尝试使用python请求库发出get请求时,它并没有提供完整的响应。你知道吗

例如,如果我调用这个URL https://www.google.com/search?q=tea+meaning来获取单词tea的含义,那么在得到的响应中,它只显示名词内容,而不是动词内容。你知道吗

from bs4 import BeautifulSoup as bs
import requests as req

headers_Get = {
    'Host': 'www.google.com',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'DNT': '1',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1'
}

url = "https://www.google.com/search?q=tea+meaning"
response = req.get(url, headers=headers_Get)

data = response.text
soup = bs(data, "html.parser")

这道汤有问题。它不包含动词内容。 为什么会这样?你知道吗

enter image description here

谢谢你。你知道吗


Tags: httpsimportcom内容searchgetbsas
2条回答

您应该选择要打印的<div>。您将获得整个页面。你知道吗

import requests
from bs4 import BeautifulSoup
url = "https://www.google.com/search?q=tea+meaning"
header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'}
page=requests.get(url,headers=header)

soup=BeautifulSoup(page.content,'html.parser')
result = soup.select_one('div.vmod').get_text()
print(result)

这段代码打印所有内容,包括动词。 嘿,如果你想得到它的含义,https://developer.oxforddictionaries.com/有一个很好的API,试着用它

问题是谷歌没有将搜索结果作为一个页面发送回去。您在浏览器中看到的大多数搜索结果都是单独的AJAX请求。您可能会在初始请求中获得一些部分数据,但它不一定与常规浏览器中看到的内容相匹配。你知道吗

要想知道如何处理漂亮的汤和请求,请尝试在关闭JavaScript的浏览器中打开链接。你知道吗

相关问题 更多 >