在 Python 中获得 Bing 个搜索结果

Get Bing search results in Python

我正在尝试制作一个可以使用 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)

实际上,您编写的代码可以正常工作,问题出在 HTTP 请求 header 中。默认情况下 urllib 使用 Python-urllib/{version} 作为 User-Agent header 值,这使得网站很容易将您的请求识别为自动生成。为避免这种情况,您应该使用可以通过 Request object 作为 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"])

P.S。看看@edd在你的问题下留下的评论。