【问题标题】:using beautifulsoup to find links inside header tags使用 beautifulsoup 查找标题标签内的链接
【发布时间】:2014-11-08 13:49:49
【问题描述】:

我正在尝试收集页面上所有标签内的所有链接,并为 125 个页面执行此操作。我创建了以下循环,但它没有获取任何链接,但也没有给我任何错误消息。

for i in xrange(125,1,-1):
    page = urllib2.urlopen("http://www.freedomworks.org/issue/budget-spending?page={}".format(i))
    soup = BeautifulSoup(page.read())
    snippet = soup.find_all('h3')
    with io.open('FWurl.txt', 'a', encoding='utf8') as logfile:
        for link in snippet.find_all('a'):
            fulllink = link.get('href')
            logfile.write(fulllink + "\n")

我认为这正是 BeautifulSoup 的用途,但我想不通。提前谢谢你。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    我认为问题在于执行snippet.find_all 会引发异常——snippet 显然是一个ResultSet 对象,您需要遍历它才能实际访问每个单独的 h3 元素。

    将您的文件修改为:

    with io.open('FWurl.txt', 'a', encoding='utf8') as logfile:
        for i in xrange(125, 1, -1):
            page = urllib2.urlopen("http://www.freedomworks.org/issue/budget-spending?page={}".format(i))
            soup = BeautifulSoup(page.read())
            snippet = soup.find_all('h3')
    
            for h3 in snippet:
                for link in h3.find_all('a'):
                    logfile.write(link.get('href') + "\n")
    

    注意:我不确定每个“h3”是否有多个“a”标签,所以为了安全起见,我遍历了h3.find_all('a')。如果每个h3 中只有一个a,您可以通过抓取第一个元素(如果存在)来提高代码效率。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-19
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 2015-12-09
      • 2017-08-04
      相关资源
      最近更新 更多