![](/img/trans.png)
[英]Navigate with Selenium and scrape with BeautifulSoup in Python
[英]Trying to Scrape Table with Python's Beautifulsoup & Selenium
正如标题所示,我正在尝试同时使用 Beautifulsoup 和 Selenium 来抓取表格。 我知道我很可能不需要这两个库,但是我想尝试使用 Selenium 的 xpathselectors 是否会有所帮助,不幸的是他们没有。
该网站可以在这里找到:
https://app.capitoltrades.com/politician/491
我正在尝试做的是在底部的“交易”下刮掉表格
这是一个截图
一旦我可以抓取表格,我将收集表格行内的 td 数据。
因此,例如,我想要在“发布日期”下的“29/Dec/2021”。 不幸的是,我没能走到这一步,因为我抓不到桌子。
这是我的代码:
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
url = 'https://app.capitoltrades.com/politician/491'
resp = requests.get(url)
#soup = BeautifulSoup(resp.text, "html5lib")
soup = BeautifulSoup(resp.text, 'lxml')
table = soup.find("table", {"class": "p-datatable-table ng-star-
inserted"}).findAll('tr')
print(table)
这会产生错误消息“AttributeError: 'NoneType' object has no attribute 'findAll'
使用 'soup.findAll' 也不起作用。
如果我尝试使用 Selenium 的 xpathselector 路由...
DRIVER_PATH = '/Users/myname/Downloads/capitol-trades/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.implicitly_wait(1000)
driver.get('https://app.capitoltrades.com/politician/491')
table = driver.find_element_by_xpath("//*[@id='pr_id_2']/div/table").text
print(table)
Chrome 继续打开,我的 Jupyter 笔记本内没有打印任何内容(可能是因为表格元素内没有直接文本[?])
我希望能够使用 Beautifulsoup 来获取表格元素,但欢迎所有答案。 感谢您为我提供的任何帮助。
根据您的 Selenium 代码:您错过了等待。
这个
driver.find_element_by_xpath("//*[@id='pr_id_2']/div/table")
命令在刚创建时返回 web 元素,即已经存在,但仍未完全呈现。
这应该会更好:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
DRIVER_PATH = '/Users/myname/Downloads/capitol-trades/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
wait = WebDriverWait(driver, 20)
driver.get('https://app.capitoltrades.com/politician/491')
table = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='pr_id_2']//tr[@class='p-selectable-row ng-star-inserted']"))).text
print(table)
根据您的 BS4 代码,您似乎使用了错误的定位器。
这个:
table = soup.find("table", {"class": "p-datatable-table ng-star-inserted"})
看起来更好(您的 class 名称中有额外的空格)。
上面的行返回 5 个元素。
所以这应该工作:
table = soup.find("table", {"class": "p-datatable-table ng-star-inserted"}).findAll('tr')
该站点有一个后端 api 可以很容易地被击中:
import requests
import pandas as pd
url = 'https://api.capitoltrades.com/senators/trades/491/false?pageSize=20&pageNumber=1'
resp = requests.get(url).json()
df = pd.DataFrame(resp)
df.to_csv('naughty_nancy_trades.csv',index=False)
print('Saved to naughty_nancy_trades.csv ')
要查看所有数据的来源,请打开浏览器的开发者工具 - 网络 - 获取/XHR 并重新加载页面,您会看到它们触发。 我已经抓取了其中一个网络调用,该页面上的所有数据还有其他调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.