我是python的新手,并尝试使用BeautifulSoup从Wikitable的第三列中提取Wikipedia page上的所有火车站名称。 我已经尝试了下面的代码,但它似乎将每一行单元格作为一组信息返回
const parent = document.querySelector('.main_container')
const image = document.querySelector('#container-1').style.backgroundImage
parent.style.backgroundImage = image
如下所示,代表表中的第一行的输出:
contentTable = soup.find('table', { "class" : "wikitable"})
cols = contentTable.find_all('td')
for col in cols:
soup.find_all("a")
print(col.get_text())
预期的数据框列工作站名称:
CG2
TE [a]
Changi Airport
樟宜机场
சாங்கி விமானநிலையம்
8 February 2002
Changi Airport
CGA
Changi
Singapore Changi Airport, Changi Airport PTB2 Bus Terminal
有人可以教我如何正确编码吗? 谢谢!
答案 0 :(得分:0)
您的程序只是简单地在Wikitable上打印每个“ td”标签的文本内容。
尝试以下方法:
contentTable = soup.find('table', {"class": "wikitable"})
trs = contentTable.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
for td in tds:
if tds.index(td) == 2:
print(td.get_text())
首先,它抓取每一行,找到该行上的每个“ td”标签,如果它是该行上的第三个“ td”标签,则打印出其内容。
答案 1 :(得分:0)
尝试
import requests
from bs4 import BeautifulSoup
# url to be scrape
URL = "https://en.wikipedia.org/wiki/List_of_Singapore_MRT_stations"
PAGE = requests.get(URL)
# get HTML content
SOUP = BeautifulSoup(PAGE.content, 'lxml') # lxml is faster then html.parser
contentTable = SOUP.find('table', {"class": "wikitable"})
rows = contentTable.findAll('tr')
for tr in rows:
columns = tr.find_all('td')
for index, td in enumerate(columns):
if index == 2:
print(td.text)