python - For循环在Beautiful Soup中迭代div

标签 python arrays beautifulsoup

我正在使用 BS 来解析职位列表网站。它工作正常,但只返回 div 的第一项。我希望它使用名为 {'class': 'job-item'} 的类迭代每个 div。我已经通读了文档并尝试了一些尝试以使其正常工作,但我只是被卡住了。

from bs4 import BeautifulSoup
import urllib2
import time

quote_page = 'https://jobbio.com/search/jobs?query=Developer&location=dublin&sector='
page = urllib2.urlopen(quote_page)

soup = BeautifulSoup(page, 'html.parser')

divs = soup.findAll({'class': 'job-item'})

for div in divs:
        role_box =  soup.find(attrs={'class': 'color-dark-grey'})
        role = role_box.text.strip() # strip() is used to remove starting and trailing
        company_box =  soup.find(attrs={'class': 'color-greenish-blue'})
        company = company_box.text.strip() # strip() is used to remove starting and trailing
        location_box =  soup.find(attrs={'class': 'color-grey'})
        location = location_box.text.strip() # strip() is used to remove starting and trailing
        url_box =  soup.find(attrs={'class': 'job-tile-actions'}).a['href']
        url_root = 'http://jobbio.com'
        url = url_root + url_box
        salary = '-'
        date = time.strftime("%d/%m/%Y")
        array = {'role':str(role), 'company': str(company), 'location': str(location), 'salary': str(salary), 'date':date, 'url': str(url)}
        print array

如果我删除 for 循环代码执行正常,所以我知道刮板工作。我只希望它为页面上的所有内容打印多个数组。这最终将进入我可以查询的数据库。

谢谢

编辑:使用调试器,问题在于循环本身(很有趣)
> /var/www/html/JobScraper/scrape.py(13)<module>()
-> divs = soup.findAll({'class': 'job-item'})
(Pdb) n
> /var/www/html/JobScraper/scrape.py(15)<module>()
-> for div in divs:
(Pdb) n
--Return--
> /var/www/html/JobScraper/scrape.py(15)<module>()->None
-> for div in divs:
(Pdb) n
--Return--
> <string>(1)<module>()->None
(Pdb) n
> /usr/lib/python2.7/bdb.py(404)run()
-> self.quitting = 1

最佳答案

改变所有soup.find()for循环到:

divs = soup.findAll(class_= 'job-item')    
for div in divs:

    div.find()

您应该从 div 开始搜索标签,而不是 soup标签,soup标签是 root HTML 文档的标签

关于python - For循环在Beautiful Soup中迭代div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43041991/

相关文章:

c# - 从 Python 调用 C# dll

c - malloc 和 realloc 数组给出意外输出

java - 复制字符串数组并删除空字符串

python - 异常类型: MissingSchema/beautifulsoup

Python戴尔驱动程序下载

python plot 和 powerlaw 适合

python - einsum 和距离计算

python - 在 SciPy 中多核上运行 SVM 代码?

php - 如何在 php 中测试数组的索引是否与数组的另一个索引相等?

python - 如何只选择具有相似ID的DIV