我正在尝试创建一个可以使用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请求标头中。默认情况下,urllib
使用Python-urllib/{version}
作为User-Agent
标头值,这使网站很容易将请求识别为自动生成的。为了避免这种情况,您应该使用自定义值,该值可以通过将Request
对象作为Request
的第一个参数来实现:
urlopen()