python - 当我尝试使用 Python 进行网络抓取表格时,为什么要乘以文本?

标签 python selenium web-scraping beautifulsoup

我正在尝试从网站上抓取表格,一切都很好,运行没有错误,但是当我在 csv 中打开它时,我看到有多个网页抓取:文本+表格,当我只需要我正在网络抓取的表格。

enter image description here

该表从第 53 行开始,我不明白。 为什么我的代码不仅抓取表格,还抓取文本?

我的代码:

from bs4 import BeautifulSoup
from selenium import webdriver
import time
import unicodecsv as csv

filename = r'output.csv'

resultcsv = open(filename, "wb")
output = csv.writer(resultcsv, delimiter=';', quotechar='"',
                    quoting=csv.QUOTE_NONNUMERIC, encoding='latin-1')

profile = webdriver.FirefoxProfile()
profile.set_preference("intl.accept_languages", "en-us")
driver = webdriver.Firefox(firefox_profile=profile)
driver.get("https://www.flightradar24.com/data/airports/bud/arrivals")
time.sleep(10)
html_source = driver.page_source
soup = BeautifulSoup(html_source, "html.parser")
print(soup)

table = soup.find('table', { "class" : "table table-condensed table-hover data-table m-n-t-15" })

datatable = []
for record in table.find_all('tr'):
    temp_data = []
    for data in record.find_all('td'):
        temp_data.append(data.text.encode('latin-1'))
    datatable.append(temp_data)

output.writerows(datatable)

resultcsv.close()

最佳答案

您的表格在 tr 标记中包含所有这些行,这就是它们附加您想要的行的原因。

您需要过滤您期望的标签的类,在您的情况下这应该有效:

for record in table.find_all('tr', class_="hidden-xs hidden-sm ng-scope"):
    temp_data = []
    for data in record.find_all("td"):
        temp_data.append(data.text.encode('latin-1'))
    datatable.append(temp_data)

关于python - 当我尝试使用 Python 进行网络抓取表格时,为什么要乘以文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300525/

相关文章:

python - 如何将列表的 numpy 列表直接作为列附加到现有的 CSV 文件?

python - 使用 glob 按特定顺序导入文件

python - matplotlib 图形 Canvas 名称

python - 足球统计 Python 抓取工具

python - 字符串列表在 python 中的转换

python-3.x - selenium.common.exceptions.WebDriverException : Message: unknown error: unable to discover open pages using ChromeDriver through Selenium

java - 如果 20% 或第 20 个测试用例测试方法失败,我如何停止 Selenium 自动化?

linux - linux 中的 IE11 webdriver 是否支持 selenium 测试?

c# - 在 c++/c# 中从哪里开始抓取/爬行?

json - 使用 VBA-JSON 从 API "error: object does not support this property or method here"中提取?