【问题标题】:Web Crawler To get Links From New Website网络爬虫从新网站获取链接
【发布时间】:2013-11-23 17:39:08
【问题描述】:

我正在尝试从新闻网站页面(从其档案之一)获取链接。我在 Python 中编写了以下代码行:

main.py 包含:

import mechanize
from bs4 import BeautifulSoup

url = "http://www.thehindu.com/archive/web/2010/06/19/"

br =  mechanize.Browser()
htmltext = br.open(url).read()

articletext = ""
soup = BeautifulSoup(htmltext)
for tag in soup.findAll('li', attrs={"data-section":"Business"}):
    articletext += tag.contents[0]

print articletext

tag.contents[0] 中的对象示例: <a href="http://www.thehindu.com/business/itc-to-issue-11-bonus/article472545.ece" target="_blank">ITC to issue 1:1 bonus</a>

但在运行它时,我收到以下错误:

File "C:\Python27\crawler\main.py", line 4, in <module>
    text = articletext.getArticle(url)
  File "C:\Python27\crawler\articletext.py", line 23, in getArticle
    return getArticleText(htmltext)
  File "C:\Python27\crawler\articletext.py", line 18, in getArticleText
    articletext += tag.contents[0]
TypeError: cannot concatenate 'str' and 'Tag' objects

有人可以帮我解决吗?我是 Python 编程的新手。谢谢和问候。

【问题讨论】:

    标签: python python-2.7 python-3.x beautifulsoup


    【解决方案1】:

    您模糊地使用了 link_dictionary。如果您不将其用于阅读目的,请尝试以下代码:

     br =  mechanize.Browser()
     htmltext = br.open(url).read()
    
     articletext = ""
     for tag_li in soup.findAll('li', attrs={"data-section":"Op-Ed"}):
        for link in tag_li.findAll('a'):
            urlnew = urlnew = link.get('href')
            brnew =  mechanize.Browser()
            htmltextnew = brnew.open(urlnew).read()            
            articletext = ""
            soupnew = BeautifulSoup(htmltextnew)
            for tag in soupnew.findAll('p'):
                articletext += tag.text
            print re.sub('\s+', ' ', articletext, flags=re.M)
    

    注意:re 用于正则表达式。为此,您导入 re 的模块。

    【讨论】:

      【解决方案2】:

      您可能希望将强大的 XPath 查询语言与更快的 lxml 模块一起使用。就这么简单:

      import urllib2
      from lxml import etree
      
      url = 'http://www.thehindu.com/archive/web/2010/06/19/'
      html = etree.HTML(urllib2.urlopen(url).read())
      
      for link in html.xpath("//li[@data-section='Business']/a"):
          print '{} ({})'.format(link.text, link.attrib['href'])
      

      @data-section='Chennai' 的更新

      #!/usr/bin/python
      import urllib2
      from lxml import etree
      
      url = 'http://www.thehindu.com/template/1-0-1/widget/archive/archiveWebDayRest.jsp?d=2010-06-19'
      html = etree.HTML(urllib2.urlopen(url).read())
      
      for link in html.xpath("//li[@data-section='Chennai']/a"):
          print '{} => {}'.format(link.text, link.attrib['href'])
      

      【讨论】:

      • 是你代码的语法正确。我收到Invalid Syntax 的错误。谢谢。
      • 是的,没关系。请注意,您需要安装 lxml 模块才能使用它。在许多方面,它是 BeautifulSoup 的更快替代品。 :)
      • 是的,我已经安装了它。我在 print 语句的最后一行遇到了上述性质的错误。
      • 你能运行你提到的代码并检查一下吗?还请告诉我您正在使用的 Python 版本。
      • 它在那里,但在 ul 的不同标签下,它被写入 archiveRestDayList。但无论如何,谢谢你的帮助。我把问题解决了。我使用了selenium 模块而不是BeautifulSoup,它工作得很好。
      【解决方案3】:

      我相信您可能想尝试访问列表项中的文本,如下所示:

      for tag in soup.findAll('li', attrs={"data-section":"Business"}):
          articletext += tag.string
      

      已编辑:关于从页面获取链接的一般评论

      可能用于收集一堆链接并稍后检索它们的最简单的数据类型是字典。

      要使用 BeautifulSoup 从页面获取链接,您可以执行以下操作:

      link_dictionary = {}
      with urlopen(url_source) as f:
          soup = BeautifulSoup(f)
          for link in soup.findAll('a'):
              link_dictionary[link.string] = link.get('href') 
      

      这将为您提供一个名为link_dictionary 的字典,其中字典中的每个键都是一个字符串,它只是&lt;a&gt; &lt;/a&gt; 标记之间的文本内容,每个值都是href 属性的值。


      如何结合你之前的尝试

      现在,如果我们将此与您之前遇到的问题结合起来,我们可以尝试以下方法:

      link_dictionary = {}
      for tag in soup.findAll('li', attrs={"data-section":"Business"}):
          for link in tag.findAll('a'):
              link_dictionary[link.string] = link.get('href') 
      

      如果这没有意义,或者您有更多问题,您需要先进行试验并尝试提出解决方案,然后再提出另一个更清晰的新问题。

      【讨论】:

      • 是的,这正是我想要做的。虽然我真正想要的是在某种数组或列表中获取href 中的链接。你能帮帮我吗?
      • 我对我的帖子进行了编辑,这可能会帮助您朝着正确的方向前进,但如果没有帮助,您将需要提出一个更好的问题(您将有先做一些实验,这样你就有一个清晰、简洁的问题)。
      • 好的,我想我现在明白你想要做什么了。请参阅上面的最终编辑。
      • 但如果我使用attrs={"data-section":"Chennai"} 而不是attrs={"data-section":"Business"},我将无法打印任何内容。能告诉我原因吗??我尝试了不同的方法,但无法获得所需的输出。
      猜你喜欢
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多