【问题标题】:Extracting string from <h1> element with logic attached从附有逻辑的 <h1> 元素中提取字符串
【发布时间】:2022-01-23 06:36:36
【问题描述】:

我正在尝试抓取一些体育比赛数据,但我的代码遇到了一些问题。最终我会将这些数据移动到数据框中,然后最终移动到数据库中。

我正在尝试抓取一些体育数据。

在代码中,我找到了我要解析的标题之一的类元素。我正在解析的 HTML 中有多个 h1。

 <div class="type-game">
      <div class="type">NHL Regular Season</div>
      <h1>Blackhawks vs. Ducks</h1>
 </div>

有了这个 HTML 结构,我怎样才能让 h1 返回一个我可以用来填充数据框的字符串?

到目前为止我尝试过的代码是:

 req = requests.get(url) # + str(page) + '/')
 soup = bs(req.text, 'html.parser')

 stype = soup.find('h1', class_ ='type-game')
 print(stype)

此代码返回“无”。我在这里查看了其他文章,到目前为止没有任何效果。

对于我的下一个问题,有没有办法为任何包含字符串的游戏创建一个 For 循环或类似的循环来遍历所有页面(网站按事件顺序编号)?

例如,如果我只想为具有 class= type-game 的 div 元素保存 h1 中包含芝加哥黑鹰队的游戏?

伪代码是这样的:

 For webpages 1 to 10000:
      if class_='type-game' 'h1' contains "Blackhawks"
           then proceed with parsing the code
      if not, skip the code and go to the next webpage

我知道这有点开放,但我有良好的 VBA 背景,尝试将这些编码思想应用于 Python 是一个挑战。

【问题讨论】:

  • 可以问一下你从哪个网站上拉?如果我能看到该站点,可能会有更简单、更有效、更可靠的方法。

标签: python html for-loop web-scraping beautifulsoup


【解决方案1】:

选择更具体的元素,例如使用css selectors

soup.select('h1:-soup-contains("Blackhawks")')

soup.select('div.type-game h1:-soup-contains("Blackhawks")')

要从标签中获取文本,只需使用 .textget_text()

for e in soup.select('h1:-soup-contains("Blackhawks")'):
    print(e.text)

示例

html='''
<div class="type-game">
      <div class="type">NHL Regular Season</div>
      <h1>Blackhawks vs. Ducks</h1>
</div>
<div class="type-game">
      <div class="type">NHL Regular Season</div>
      <h1>Hawks vs. Ducks</h1>
</div>
<div class="type-game">
      <div class="type">NHL Regular Season</div>
      <h1>Ducks vs. Blackhawks</h1>
</div>
'''

soup = BeautifulSoup(html,'lxml')

for e in soup.select('h1:-soup-contains("Blackhawks")'):
    print(e.text)

输出

Blackhawks vs. Ducks
Ducks vs. Blackhawks

编辑

for e in soup.select('div.type-game h1'):
    if 'Blackhawks' in e:
        pint(e.text)#or do what ever is to do

【讨论】:

  • 感谢您的回复,如果我不想像我上面所说的那样具体到一个团队,有什么办法可以得到 h1 中的任何内容?又名捕获所有游戏?
  • 当然,看看添加了一个编辑只是迭代soup.select('div.type-game h1')并使用.text
猜你喜欢
  • 2019-03-04
  • 2013-12-10
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多