【问题标题】:Find multiple scrape data inside the same <div> in python and beautifulsoup在python和beautifulsoup中查找同一<div>内的多个抓取数据
【发布时间】:2018-04-10 20:09:49
【问题描述】:

使用 beautifulsoup 从 div 标签中提取单个数据字符串很简单。但是如果我需要来自同一个 div 类标签的更多结果怎么办? “参考编号:”之后的数字,“日期:”之后的日期和“注册日期:”日期?那是来自同一个 div 标签“right-col”的三个字符串。

你会推荐什么? - 正则表达式? - 使用 beautifulsoup 可以获得多个“兄弟姐妹”吗?

<div class="right-col">
  <div>Reference no: 2017-598760</div>
  <div>date:<span class="label label-info">2017-12-15</span>
  </div>
  <div>RegistrationDate: 2017-10-29</div>
</div>

【问题讨论】:

  • thisthis
  • 主 div 中的内容是动态的吗?内部变化的div数量?您可以使用 beautifulsoup 循环浏览内容。
  • 没有。内容不是动态的。都是静态信息。但每页有 10 个“right-col”,信息不同。
  • 能否提供页面链接?
  • 当然。 doffin.no/Notice。我为你翻译了英文“right-col”div标签里面的内容,所以请注意你现在看到的不是英文。

标签: python regex web-scraping beautifulsoup


【解决方案1】:

您可以将找到的每个 div 转换为 html,然后再次找到所有子 div:

divs = page.find_all('div', attrs={'class': 'right-col'})


for div in divs:
    div_to_html = bs.BeautifulSoup(div.__str__(),'lxml')

    sub_divs = div_to_html.find_all('div')

    reference_no = sub_divs[1].text
    reference_no = reference_no.replace('Doffin referanse: ', '')

    print(reference_no)

    registration_date = ''
    date = ''    

    if(len(sub_divs) == 4):
        date = sub_divs[2].text
        date = date.replace('Tilbudsfrist: ', '')
        registration_date = sub_divs[3]
    else:
        registration_date = sub_divs[2] 

    registration_date = registration_date.replace('Kunngjøringsdato: ', '')

【讨论】:

  • 您的代码完美运行!我努力编码非英文字母,但在替换之前将“registration_date”编码为 utf-8,一切正常。
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 2023-03-05
  • 2019-09-03
  • 2018-12-02
相关资源
最近更新 更多