首页 > 解决方案 > 如何清理这个网络爬虫

问题描述

我想从网页上抓取一个表格,但是有两个带有相同标签的表格。

我感兴趣的表格是“事件时间线”。

我的问题是我的代码将我想要的表格作为一个整体打印出来,并且不按列/行分隔。

理想情况下,我希望将其按字段分解。

有没有办法清理这个刮擦

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)

标签: pythonseleniumweb-scraping

解决方案


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


推荐阅读