python - 如何清理这个网络爬虫
问题描述
我想从网页上抓取一个表格,但是有两个带有相同标签的表格。
我感兴趣的表格是“事件时间线”。
我的问题是我的代码将我想要的表格作为一个整体打印出来,并且不按列/行分隔。
理想情况下,我希望将其按字段分解。
有没有办法清理这个刮擦
from selenium import webdriver
import time
driver = webdriver.Chrome()
import pandas as pd
val=[]
driver.get('https://www.aan.com/MSA/Public/Events/Details/13419')
page_source = driver.page_source
element2=driver.find_element_by_tag_name('tbody').text.strip()
print(element2)
解决方案
Selenium 的目的更多是在网络自动化上,因此我将使用网络抓取包来回答您的问题BeautifulSoup
。
此答案使用您的代码获取页面的 HTML 文件,但更有效的解决方案是Request
包。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import pandas as pd
driver = webdriver.Chrome()
val = []
# Suggest using the Request package to obtain the HTML source code
driver.get('https://www.aan.com/MSA/Public/Events/Details/13419')
page_source = driver.page_source
# element2 = driver.find_element_by_tag_name('tbody')
# Declare a BeautifulSoup Object
soup = BeautifulSoup(driver.page_source, 'html.parser')
tbody = soup.find("tbody") #Find the first tbody
rows = tbody.find_all("tr") #Find all the rows
for row in rows:
rowVal = [] #Create an array to store the value
tds = row.find_all("td") #Find all the cells in the row
for td in tds:
rowVal.append(td.get_text().strip()) #Obtain text of the cell
print(rowVal) #Print them, or do anything else
推荐阅读
- ruby-on-rails - 设计忘记密码提交按钮间歇性工作
- service - 将服务引用放入域模型的架构缺点?(爪哇)
- python - 大型 CSV 文件处理
- python - 在Flask中按下按钮时如何获取HTML标签?
- spring - 在 Junit 测试运行期间,@Mockbean 和 @Qualifer 抛出
- java - 重复文件的重复 git 历史记录
- amazon-web-services - 是否可以删除 AWS ElastiCache redis 集群上的所有密钥?
- java - libGDX 中的 keyDown() 方法如何正常工作?
- php - 如何使用“ga”命令通过 Analytics.js 向谷歌分析发送购买请求?
- python - 更改列表中字典中键的值