【问题标题】:using BeautifulSoup to find divs within a div使用 BeautifulSoup 在 div 中查找 div
【发布时间】:2014-12-27 22:42:54
【问题描述】:

我正在尝试让 BeautifulSoup 查找所有五个具有“博客框”类的 div,然后在每个 div 中查找并找到具有“日期”类和“右框”类的 div然后打印那些。我需要它来打印日期,然后立即打印相关文本,这就是为什么我不能直接查找“日期”和“右框”div。

for i in xrange(3, 1, -1):
       page = urllib2.urlopen("http://web.archive.org/web/20090204221349/http://www.americansforprosperity.org/nationalblog?page={}".format(i))
       soup = BeautifulSoup(page.read())
       snippet = soup.find_all('div', attrs={'class': 'blog-box'})
       print snippet
       for div in snippet:
           date =  soup.find('div', attrs={'class': 'date'})
           text = soup.find('div', attrs={'class': 'right-box'})
           print date.text
           print text.text

但我运行它,它会打印第一个日期和文本 div 五次,然后停止。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您似乎不小心在内部循环中使用了soup,而不是循环变量div。试试:

    for ...:
       ...
       for div in snippet:
           date = div.find('div', attrs={'class': 'date'})  # <-- changed here
           text = div.find('div', attrs={'class': 'right-box'})  # <--changed here
           print date.text
           print text.text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 2019-07-16
      相关资源
      最近更新 更多