【发布时间】:2021-08-23 15:27:10
【问题描述】:
我创建了一个脚本来解析来自 htmlfile link 的几个数据点,并根据 this format 将其写入 csv 文件。
我确实使用已在脚本中定义的选择器相应地定位字段,但我无法以正确的方式对输出进行分层,以便稍后将它们写入 csv 文件。
数据点的位置:
Nature of association
`from 1st table`
Purpose
In cash (Previous balance)
`from 2nd table`
Donor Name
Address
`from 3rd table`
Country Name
Amount
这是我尝试过的 (I suppose the htmlfile link works):
import requests
from bs4 import BeautifulSoup
file_link = 'https://filebin.redpill-linpro.com/zj2qqc27va5fatm0/index.html'
res = requests.get(file_link)
soup = BeautifulSoup(res.text,"lxml")
nature_of_asso = soup.select_one("td:contains('Nature of association') + td").get_text(strip=True)
for purpose_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Purpose')) tr")[3:]:
try:
purpose = purpose_tr.select_one('td:nth-of-type(2)').get_text(strip=True)
except AttributeError: purpose = ""
try:
in_cash = purpose_tr.select_one('td:nth-of-type(3)').get_text(strip=True)
except AttributeError: in_cash = ""
print(purpose,in_cash)
for donor_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Donor Name')) tr")[2:]:
try:
donor_name = donor_tr.select_one('td:nth-of-type(2)').get_text(strip=True)
except AttributeError: donor_name = ""
try:
address = donor_tr.select_one('td:nth-of-type(3)').get_text(strip=True)
except AttributeError: address = ""
print(donor_name,address)
for country_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Country Name')) tr")[1:]:
try:
country = country_tr.select_one('td:nth-of-type(2)').get_text(strip=True)
except AttributeError: country = ""
try:
amount = country_tr.select_one('td:nth-of-type(3)').get_text(strip=True)
except AttributeError: amount = ""
print(country,amount)
如何根据上图安排输出以便将其写入 csv 文件?
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup