from bs4 import BeautifulSoup
import requests
import urllib.parse
import urllib.request
import re
i = ("james")
url = ("https://www.bing.com/search?q=" + i)
values = {'s': 'basics',
'submit':'search'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
respData = resp.read()
cites = re.findall(r'<cite>(.*?)</cite>', str(respData))
print (cites)
输出[]正确的响应是列表形式的一堆链接有时会显示结果。
如果得到[]
,请使用浏览器在Bing中检查查询。如果看到:
There are no results for <your query here>
Check your spelling or try different keywords
由于没有返回结果,因此使用BeautifulSoup获取此查询的[]
是正常的。
仅当使用真正的完整User-Agent
标头时,我才能获取数据
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'
如果我不使用'User-Agent'
或仅使用'Mozilla/5.0'
,那么我没有得到结果
不需要其他元素,但我将其保留为代码中的注释。
也许它的代码将被使用更长或更长时间,然后它可能需要cookie或其他元素才能正常工作。
我用来测试不同的params
,headers
,Session
/ cookies
的代码
from bs4 import BeautifulSoup
import requests
#import webbrowser
#s = requests.Session()
#headers = {
# 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'
#}
#response = s.get("https://www.bing.com", headers=headers)
#print(response.status_code)
params = {
'q': 'james',
# 'go': 'Wyszukaj', # `Search` in my native, Polish language
# 'qs': 'ds',
# 'form': 'QBRE'
}
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0',
# 'User-Agent': 'Mozilla/5.0',
# 'Referer': 'https://www.bing.com',
}
response = requests.get("https://www.bing.com/search", params=params, headers=headers)
html = response.text
#with open('temp.html', 'w') as f:
# f.write(html)
#webbrowser.open('temp.html')
soup = BeautifulSoup(html, 'html.parser')
cites = soup.find_all('cite')
print(cites)