我正在尝试进行网络抓取并使用以下代码:
import mechanize
from bs4 import BeautifulSoup
url = "http://www.thehindu.com/archive/web/2010/06/19/"
br = mechanize.Browser()
htmltext = br.open(url).read()
link_dictionary = {}
soup = BeautifulSoup(htmltext)
for tag_li in soup.findAll('li', attrs={"data-section":"Chennai"}):
for link in tag_li.findAll('a'):
link_dictionary[link.string] = link.get('href')
print link_dictionary[link.string]
urlnew = link_dictionary[link.string]
brnew = mechanize.Browser()
htmltextnew = brnew.open(urlnew).read()
articletext = ""
soupnew = BeautifulSoup(htmltextnew)
for tag in soupnew.findAll('p'):
articletext += tag.text
print articletext
我无法使用它获得任何打印值。但是在使用 attrs={"data-section":"Business"} 而不是 attrs={"data-section":"Chennai"} 我能够得到所需的输出。有人可以帮助我吗?
请您参考如下方法:
在抓取之前阅读网站的服务条款
如果您在 Chrome 中使用 firebug 或 inspect element,您可能会看到一些在使用 Mechanize 或 Urllib2 时看不到的内容。
例如,当您查看您发出的页面的源代码时。 (在 Chrome 中右键单击查看源代码)。并搜索 data-section 标签,您不会看到任何 chennai 标签,我不是 100% 确定,但我会说这些内容需要由 Javascript 填充..ETC。这需要浏览器的功能。
如果我是你,我会用 selenium 打开页面,然后从那里获取源页面,这样收集的 HTML 将更像你在浏览器中看到的。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
driver = webdriver.Firefox()
driver.get("URL GOES HERE")
# I noticed there is an ad here, sleep til page fully loaded.
time.sleep(10)
soup = BeautifulSoup(driver.page_source)
print len(soup.findAll(...}))
# or you can work directly in selenium
...
driver.close()
我的输出是 8
