【问题标题】:I have a trouble with parsing a table in a web page我在解析网页中的表格时遇到问题
【发布时间】:2020-02-05 18:38:39
【问题描述】:

我正在尝试使用 selenium 和 BeautifulSoup 从网页 (https://en.wikipedia.org/wiki/2018%E2%80%9319_Premier_League) 中提取一个表格。

但我被解析表困住了。 我只想要网页中的一张表,即“联赛表”,但无论我尝试过什么,都会收到错误消息。

这是我尝试过的代码。

 import selenium 
from bs4 import BeautifulSoup
from selenium import webdriver
import time
driver.get("https://google.com")
elem = driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
elem.send_keys("2018 epl")
elem.submit()
try:
   print(driver.title)
driver.find_element_by_partial_link_text("Wikipedia").click()
website = requests.get(driver.current_url).text

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

然后我遇到了麻烦.. 我已经尝试了几个代码,其中一个如下。

rows=soup.find_all('td')

那么你能帮我完成我的代码吗? 非常感谢。

【问题讨论】:

  • 您收到的错误信息是什么?
  • 您提到了维基百科页面问题,但您的代码与谷歌搜索更相关。您能否提供一个相关示例,直接指向您提到的页面并尝试解析表格?

标签: python selenium parsing web-scraping beautifulsoup


【解决方案1】:

您可以只使用 pandas read_html 并通过适当的索引进行提取。但是,我将展示使用 bs4 4.7.1 + 的 :has 选择器来确保您选择具有 id League_table 的 h2,然后选择直接兄弟组合器来获取相邻表

from bs4 import BeautifulSoup as bs
import requests
import pandas as pd

r = requests.get('https://en.wikipedia.org/wiki/2018%E2%80%9319_Premier_League')
soup = bs(r.content, 'lxml')
table = pd.read_html(str(soup.select_one('h2:has(#League_table) + table')))
print(table)

只需阅读_html

import pandas as pd

tables = pd.read_html('https://en.wikipedia.org/wiki/2018%E2%80%9319_Premier_League')
print(tables[4])

【讨论】:

  • 非常感谢!!这正是我想要的!!我实际上尝试使用循环过程,所以我需要指定确切的表名。感谢您的帮助。
【解决方案2】:

也许这会帮助你开始:

import requests
from bs4 import BeautifulSoup

respond = requests.get('https://en.wikipedia.org/wiki/2018%E2%80%9319_Premier_League')
soup = BeautifulSoup(respond.text, 'lxml')
table = soup.find_all('table', {'class': 'wikitable'})

【讨论】:

    【解决方案3】:

    我通过在您的代码下方使用此代码获得了表格。

    soup.body.find_all("table", class_="wikitable")[3]

    我通过试错法找到了表,即首先查看表的类,然后使用 find_all,然后列出各个项目并验证输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多