BeautifulSoup无法找到标签。

3

我尝试从一个网站上获取数据,但是find()方法找不到标签。以下是我的代码:

import urllib2 
from bs4 import BeautifulSoup

url='http://www.jbhifi.com.au/computers/laptop-notebook/'
req=urllib2.Request(url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 5.1)          AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36'})
webpage=urllib2.urlopen(req)
content=webpage.read()
soup=BeautifulSoup(content)
x=soup.find("div",attrs={'id':'content-two'})
print x  #return None

然后,我只找到了HTML漂亮的解析器头部。
head=soup.find('head')
print head # print out content within <head>tag
body=soup.find('body')
print body # Print None

我真的很困惑。我以前用过beautifulsoup几次。这是我第一次遇到这个问题。有人知道如何解决这个问题吗?谢谢。

问题已经解决。我卸载了beautifulsoup 4.2,然后安装了beautifulsoup 4.3。现在代码可以正常运行了。


你实际上想从网站上爬取什么? - Venkateshwaran Selvaraj
2个回答

2
代码运行得非常好。你认为 'x' 会返回 None 的假设是错误的。
(Pdb) print x is None
False
(Pdb) print str(x)[:100]
<div id="content-two" style="float:right;width:828px;">
<div style="padding-bottom:7px;"><a href="ht

我已经尝试过了,但我仍然无法获取标签。soup.find("div",attrs={'id':'content-two'})返回NoneType值。 - user2659536
1
我卸载了bs4.2并安装了4.3。现在代码可以运行了!谢谢。 - user2659536

1

您可以检查。

请确保要解析的代码位于页面上。

view-source:chrome-extension://http://www.jbhifi.com.au/computers/laptop-notebook/

如果不存在,则由JavaScript创建HTML代码。在这种情况下,使用Selenium或查找生成HTML代码的JavaScript部分。

在JavaScript中生成HTML代码有两种方法。

第一种方法是使用JavaScript生成HTML代码 => 推荐使用selenium + bs4 + requests

第二种方法是在服务器收到数据后使用JavaScript生成HTML代码 => 推荐使用bs4 + requests


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接