抓取bing搜索无结果

时间:2020-07-27 16:11:25

标签: python web-scraping beautifulsoup python-requests

我使用下面的代码从bing抓取结果,当我看到抓取的网页时,它说“ python没有结果”。 但是当我在浏览器中搜索时没有问题。

import requests
from bs4 import BeautifulSoup

term = 'python'
url = f'https://www.bing.com/search?q={term}&setlang=en-us'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify())

我搜索了,但没有发现任何类似的问题

3 个答案:

答案 0 :(得分:3)

在请求获取值时,您需要传递user-agent

import requests
from bs4 import BeautifulSoup

term = 'python'
url = 'https://www.bing.com/search?q={}&setlang=en-us'.format(term)
headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
response = requests.get(url,headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify())

答案 1 :(得分:0)

由于Bing是一个动态网站,因此Javascript会生成代码,因此您将无法仅使用Beautifulsoup对其进行抓取。相反,我建议使用selenium,它会打开一个浏览器,您可以使用Beautifulsoup控制和解析代码。

对于任何其他动态编码的网站,包括Google和许多其他网站,同样如此。

答案 2 :(得分:0)

您也可以使用第三方解决方案,例如 SerpApi。这是一个免费试用的付费 API。我们为您处理代理、解析验证码并解析所有丰富的结构化数据。

示例 Python 代码(也可在其他库中使用):

from serpapi import GoogleSearch

params = {
  "api_key": "secret_api_key",
  "engine": "bing",
  "q": "Apple"
}

search = GoogleSearch(params)
results = search.get_dict()

查看documentations了解更多详情。

免责声明:我在 SerpApi 工作。