【问题标题】:Unable to find div class on page无法在页面上找到 div 类
【发布时间】:2020-10-10 04:33:02
【问题描述】:

我无法在以下代码中找到 div 类。

网址如下:

https://www.oddsportal.com/basketball/usa/nba/los-angeles-lakers-miami-heat-IqLamQfL/#over-under;1

我的代码如下:

html_doc = urllib.request.urlopen(new_url).read()
odds_soup = BeautifulSoup(html_doc, 'html.parser')
table_header = odds_soup.find_all('div', {'id' : "odds-data-table", 'class' : 'bt-2'})
list = []
table_containers = []
for tag in table_header:
    table_containers += tag.find_all('div', {'class' : 'table-container'})

但是代码只返回一个空的 table_containers 列表。我不知道为什么,非常感谢一些帮助。

查看网站后,如下所示:

【问题讨论】:

  • 尝试将解析器更改为html5lib 执行pip install html5lib,我认为还建议使用requests 而不是urllib

标签: python python-3.x selenium web-scraping beautifulsoup


【解决方案1】:

您找不到它的原因是您的table_header 找不到任何东西,而您没有从您的table_header 得到任何东西的原因是因为您有一个404 状态码。你可以通过.status_code 来检查你的状态码并打印出来。

来源Wikipedia

HTTP 404, 404 Not Found, 404, 404 错误, Page Not Found, File Not 找到或未找到服务器错误消息是超文本传输 协议 (HTTP) 标准响应代码,在计算机网络中 通信,表示浏览器能够通信 使用给定的服务器,但服务器找不到什么...

我对您的代码进行了一些修改并打印出status code,上面写着404。对于为什么它得到一个404status code的解决方案你可能想看看这个answer或者你可以使用selenium作为答案之一。祝你好运!

import requests
from bs4 import BeautifulSoup

link = "https://www.oddsportal.com/basketball/usa/nba/los-angeles-lakers-miami-heat-IqLamQfL/#over-under;1"

html_doc = requests.get(link)
print(html_doc.status_code)
odds_soup = BeautifulSoup(html_doc.content, 'html5lib')

table_header = odds_soup.find('div',{"id":"odds-data-table"})


'''
list = []
table_containers = []
for tag in table_header:
    table_containers += tag.find_all('div', {'class' : 'table-container'})
'''

输出:

404
[Finished in 2.1s]

【讨论】:

    【解决方案2】:

    只需像这样选择它们:

    soup.find_all("div", class_="table-header-light odd first")
    

    【讨论】:

      【解决方案3】:

      需要为此使用 selenium 并传递给 BS4。然后 .append() 到你的列表 或打印出来。

      driver = webdriver.Chrome()
      driver.get('https://www.oddsportal.com/basketball/usa/nba/los-angeles-lakers-miami-heat-IqLamQfL/#over-under;1')
      odds_soup = BeautifulSoup(driver.page_source , 'html.parser')
      table_header = odds_soup.find_all("div", class_="table-header-light odd first")
      for tag in table_header:
          print(tag)
      

      展示

      <div class="table-header-light odd first"><strong><a href="" onclick="page.togleTableContent('P-201.50-0-0',this);return false;">Over/Under +201.5 </a></strong><span class="avg chunk-odd-payout"></span><span class="avg chunk-odd nowrp"></span><span class="avg chunk-odd nowrp"></span><span class="odds-cnt">(0)</span><span class="odds-co"><a class="more" href="" onclick="page.togleTableContent('P-201.50-0-0',this);return false;">Compare odds</a></span></div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-19
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 2017-11-15
        • 1970-01-01
        相关资源
        最近更新 更多