python - 属性错误 :'NoneType' 对象没有属性 'parent'

标签 python web-scraping beautifulsoup urllib attributeerror

from urllib.request import urlopen
from bs4 import BeautifulSoup
html= urlopen("http://www.pythonscraping.com/pages/page3.html")
soup= BeautifulSoup(html.read())
print(soup.find("img",{"src":"../img/gifts/img1.jpg"
}).parent.previous_sibling.get_text())

上面的代码工作正常但下面的代码不行。它给出了一个如上所述的属性错误。谁能告诉我原因?

from urllib.request import urlopen       
from bs4 import BeautifulSoup
html= urlopen("http://www.pythonscraping.com/pages/page3.html")
soup= BeautifulSoup(html.read())
price =soup.find("img",{"src=":"../img/gifts/img1.jpg"
}).parent.previous_sibling.get_text()
print(price)

谢谢! :)

最佳答案

如果比较第一个和第二个版本,您会注意到:

首先: soup.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()

  • 注意:“src”

第二个 soup.find("img","src=":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()

  • 注意:"src="

第二个代码返回 Attribute Error:'NoneType' object has no attribute 'parent' because it couldn't find src=="../img/gifts/img1.jpg " 在提供的汤中。

因此,如果您在第二个版本中删除 =,它应该可以工作。


顺便说一句,你应该明确你想使用哪个解析器,否则 bs4 将返回以下警告:

UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change code that looks like this:

BeautifulSoup([your markup])

to this:

BeautifulSoup([your markup], "lxml")

因此,如警告消息中所述,您只需将 soup = BeautifulSoup(html.read()) 更改为 soup = BeautifulSoup(html.read(), 'lxml '),例如。

关于python - 属性错误 :'NoneType' 对象没有属性 'parent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478806/

相关文章:

python - 为什么使用 pandas.assign 而不是简单地初始化新列?

Python:替换全局变量

python - 向 web2py 表单添加额外的验证要求?

python - 如何避免机器人检测?

python - 使用多个表进行时间表网络抓取 (Python)

python - 从数据框中删除顶部标题

python - 为什么在 Python 中修改父框架仅适用于模块框架?

java - 如何使用 Boilerpipe 从网页中提取新闻内容?

javascript - 如何使用 beautiful soup 将 javascript 添加到 html 中?

python - 使用 python urllib2 发送 POST 请求并获得响应