【问题标题】:Getting Different Results For Web Scraping为网页抓取获得不同的结果
【发布时间】:2013-11-23 22:49:48
【问题描述】:

我正在尝试进行网络抓取并使用以下代码:

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"} 时,我能够获得所需的输出。有人可以帮我吗?

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup web-crawler


    【解决方案1】:

    在抓取之前阅读网站的服务条款

    如果您在 Chrome 中使用 firebug 或 inspect element,您可能会看到一些在使用 Mechanize 或 Urllib2 时看不到的内容。

    例如,当您查看您发出的页面的源代码时。 (在 Chrome 中右键单击查看源代码)。并搜索data-section 标签,您将看不到chennai 的任何标签,我不是100% 确定,但我会说这些内容需要由Javascript ..etc 填充。这需要浏览器的功能。

    如果我是你,我会使用 selenium 打开页面,然后从那里获取源页面,那么以这种方式收集的 HTML 将更像你在浏览器中看到的内容。

    Cited here

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多