Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Css 使用BeautifulSoup时丢失信息_Css_Python 3.x_Beautifulsoup_Css Selectors - Fatal编程技术网

Css 使用BeautifulSoup时丢失信息

Css 使用BeautifulSoup时丢失信息,css,python-3.x,beautifulsoup,css-selectors,Css,Python 3.x,Beautifulsoup,Css Selectors,我正在遵循“用Python自动化无聊的东西”的指南 练习一个名为“项目:”我觉得很幸运“谷歌搜索”的项目 但是CSS选择器什么也不返回 import requests,sys,webbrowser,bs4,pyperclip if len(sys.argv) > 1: address = ' '.join(sys.argv[1:]) else: address = pyperclip.paste() res = requests.get('http://google.co

我正在遵循“用Python自动化无聊的东西”的指南 练习一个名为“项目:”我觉得很幸运“谷歌搜索”的项目

但是CSS选择器什么也不返回

import requests,sys,webbrowser,bs4,pyperclip
if len(sys.argv) > 1:
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

res = requests.get('http://google.com/search?q=' + str(address))
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,"html.parser")
linkElems = soup.select('.r a')
for i in range (5):
    webbrowser.open('http://google.com' + linkElems[i].get('href'))**
我已经在空闲shell中测试了相同的代码

看来

linkElems = soup.select('.r') 
一无所获

在我检查了beautiful soup返回的值之后

soup = bs4.BeautifulSoup(res.text,"html.parser")
我发现所有的
class='r'
class='rc'
都无缘无故地消失了。 但它们存在于原始HTML文件中


请告诉我为什么以及如何避免此类问题

要在定义了HTML的类
r
中获取HTML版本,必须在标题中设置
用户代理

import requests
from bs4 import BeautifulSoup

address = 'linux'

headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'}

res = requests.get('http://google.com/search?q=' + str(address), headers=headers)
res.raise_for_status()
soup = BeautifulSoup(res.text,"html.parser")

linkElems = soup.select('.r a')

for a in linkElems:
    if a.text.strip() == '':
        continue
    print(a.text)
印刷品:

Linux.orghttps://www.linux.org/
Puhverdatud
Tõlgi see leht
Linux – Vikipeediahttps://et.wikipedia.org/wiki/Linux
Puhverdatud
Sarnased
Linux - Wikipediahttps://en.wikipedia.org/wiki/Linux

...and so on.

非常感谢你,它起作用了!但我还是不知道答案reason@Tritium一些网站根据
用户代理返回不同的HTML版本。谷歌就是其中之一。但是,是的,有时候很难找到它——而且它的变化是不可预测的。