python - 使用 BeautifulSoup 在 div 中查找 div

标签 python beautifulsoup

我试图让 BeautifulSoup 查找所有五个类为“blog-box”的 div,然后在每个 div 中查找并找到类为“date”和类“right-box”的 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 五次,然后停止了。

最佳答案

您似乎不小心在内循环中使用了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

关于python - 使用 BeautifulSoup 在 div 中查找 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672131/

相关文章:

java - 确定二叉树叶子是否为路径中最大值的函数

python - 在 docker 环境中 pip install git+url

Python 字符串处理、Unicode 和 Beautiful Soup

python - 由于无法选择表 id 属性,如何使用 BeautifulSoup 抓取表?

python - Django - 错误 : ORA-01017: invalid username/password; logon denied

python - 将数据框 append 到空变量

python - 将多个列表数据转换为字典

python - 找不到别名的词法分析器

python - 正则表达式for循环在python中的列表

python - 关于请求 url 响应 404,但在浏览器中成功并抓取标签的问题