【问题标题】:Get Bing search results in Python在 Python 中获取 Bing 搜索结果
【发布时间】:2020-04-15 10:21:05
【问题描述】:

我正在尝试制作一个可以使用 Python 获取 Bing 搜索结果的聊天机器人。我尝试了许多网站,但它们都使用旧的 Python 2 代码或 Google。我目前在中国,无法访问 YouTube、Google 或与 Google 相关的任何其他内容(也无法使用 Azure 和 Microsoft Docs)。我希望结果是这样的:

This is the title
https://this-is-the-link.com

This is the second title
https://this-is-the-second-link.com

代码

import requests
import bs4
import re
import urllib.request
from bs4 import BeautifulSoup
page = urllib.request.urlopen("https://www.bing.com/search?q=programming")
soup = BeautifulSoup(page.read())
links = soup.findAll("a")
for link in links:
    print(link["href"])

它给了我

/?FORM=Z9FD1
javascript:void(0);
javascript:void(0);
/rewards/dashboard
/rewards/dashboard
javascript:void(0);
/?scope=web&FORM=HDRSC1
/images/search?q=programming&FORM=HDRSC2
/videos/search?q=programming&FORM=HDRSC3
/maps?q=programming&FORM=HDRSC4
/news/search?q=programming&FORM=HDRSC6
/shop?q=programming&FORM=SHOPTB
http://go.microsoft.com/fwlink/?LinkId=521839
http://go.microsoft.com/fwlink/?LinkID=246338
https://go.microsoft.com/fwlink/?linkid=868922
http://go.microsoft.com/fwlink/?LinkID=286759
https://go.microsoft.com/fwlink/?LinkID=617297

任何帮助将不胜感激(我在 Ubuntu 上使用 Python 3.6.9)

【问题讨论】:

  • 欢迎。您是否尝试过进行一些研究,也许已经编写了一些代码?
  • 我试过 BeautifulSoup,但它并没有真正起作用。它只是向我显示了一些 microsoft.com 和 weibo.com,仅此而已
  • 很高兴分享你的努力。
  • 你尝试过做什么?重要的是要解释您尝试过的内容、可能未执行预期结果的当前代码或为最终目标付出的​​努力。您可能会因为缺少“期望其他人完成工作”的代码而被否决
  • 欢迎您!我不建议网络抓取大型供应商。他们很可能有预防措施。相反,寻找大多数供应商提供的可用 API(特别是如果它是合法操作),以执行您想要执行的操作。一个快速的在线搜索产生了他们的docspricing 对于 POC 大小的项目是免费的。

标签: python web-scraping bing


【解决方案1】:

实际上,您编写的代码工作正常,问题出在 HTTP 请求标头中。默认情况下urllib 使用Python-urllib/{version} 作为User-Agent 标头值,这使得网站很容易将您的请求识别为自动生成的。为避免这种情况,您应该使用自定义值,该值可以通过将Request 对象作为urlopen() 的第一个参数来实现:

from urllib.parse import urlencode, urlunparse
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup

query = "programming"
url = urlunparse(("https", "www.bing.com", "/search", "", urlencode({"q": query}), ""))
custom_user_agent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
req = Request(url, headers={"User-Agent": custom_user_agent})
page = urlopen(req)
# Further code I've left unmodified
soup = BeautifulSoup(page.read())
links = soup.findAll("a")
for link in links:
    print(link["href"])

附注查看@edd 在您的问题下留下的评论。

【讨论】:

  • 有效!我设法获得了一个 API 密钥,它成功地读取了所有搜索结果。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2021-09-30
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多