【问题标题】:Request does not show all elements of website code请求未显示网站代码的所有元素
【发布时间】:2021-01-02 23:09:03
【问题描述】:

我试图从一个篮球比赛的博彩网站上获取赔率。 我打开了两个屏幕,一个带有 python,一个带有我检查元素的网站。 但是,当我尝试通过查看网站的元素来浏览汤时,代码突然返回:

<div id="table-matches"></div>

Process finished with exit code 0

但是,当我查看网站的元素时,我仍然应该能够进一步导航。有谁知道汤怎么可能不包含网站上的所有元素(/代码行)?我应该如何更改我的代码,以便我可以提取每场比赛的赔率? 这是我的代码:

import bs4
import lxml
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup


page = 'https://www.oddsportal.com/matches/basketball/20210102/?r=3'
req = Request(page, headers={'User-Agent': 'Mozilla/8.0'})
webpage = urlopen(req).read()
page_soup = soup(webpage, 'html.parser')

odds = page_soup.body.div.div.find('div', id='mother').find('div', id='wrap').div.div.div.find('div',id='col-left').find('div',id='col-content').find('div',id='table-matches')
print(odds)

通过查看网站上的元素,我认为我必须使用.find('table', class_='table-main') 来提取表格。但是,这样做会返回:

None

【问题讨论】:

  • 数据是用javascript加载的,所以需要使用requests-html或者python selenium来抓取渲染的页面。
  • 我可以推荐 Selenium/Python 吗?

标签: python beautifulsoup python-requests screen-scraping


【解决方案1】:

正如 Eric 所说,网页是用 JS 加载的,这意味着当您请求它时数据不存在。这可能就是您要查找的数据。

代码不包括表头。

from requests_html import HTMLSession

session = HTMLSession()
r = session.get("https://www.oddsportal.com/matches/basketball/20210102/?r=3")
r.html.render()
page_soup = soup(r.html.html, "html.parser")

table = page_soup.table

table_rows = table.find_all("tr")

for tr in table_rows:

    td = tr.find_all("td")
    row = [i.text for i in td]
    if row:
        print(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多