python - 如何在Python上解析网站上的特定HTML表

标签 python web-scraping html-parsing

我是使用 python 进行网页抓取的初学者。我正在尝试解析兰卡威岛的礼拜场所表。这是我指的网站http://www.jaik.gov.my/?page_id=658

我在 python 中输入了以下内容:-

import requests

import lxml.html as lh

import pandas as pd

langkawi_url = 'http://www.jaik.gov.my/?page_id=658'

page = requests.get(langkawi_url)

doc = lh.fromstring(page.content)

tr_elements = doc.xpath('//td')

[len(T) for T in tr_elements[:12]]

tr_elements = doc.xpath('//tr')

col = []
i = 0

for t in tr_elements[0]:
    i+=1
    name=t.text_content()
    print("%d:%s" % (i,name))
    col.append((name,[]))

显然我得到的输出是这样的:-

1:Sun
2:Mon
3:Tue
4:Wed
5:Thu
6:Fri
7:Sat

我希望得到这个:-

1:BIL
2:KARIAH MASJID
3:ALAMAT
4:MUKIM

非常感谢您的建议和指导。

谢谢!

最佳答案

尝试将代码更改为:

tr_elements = doc.xpath('//td/strong')
col = []
for t in tr_elements:
    col.append(t.text)
print(col)

输出:

['BIL', 'KARIAH MASJID', 'ALAMAT', 'MUKIM']

关于python - 如何在Python上解析网站上的特定HTML表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240202/

相关文章:

python - 如何使用 python Bokeh 绘制圆图 LinearColorMapper

html - 将我的 HTML 从一种形式转换为另一种形式

python - 如何在 Scrapy 中暂停爬虫

python - 将 BeautifulSoup 指向某个 <tr> 类

python - 从(相对)父文件夹导入 BeautifulSoup,并在其旁边导入一个 html 解析器

python - 访问 pyunittearDown 中的测试状态

python - 为什么在尝试使用 SharedMemoryManager (python 3.8) 替代 BaseManager 时会出现 NameError 错误?

python - 在 Pandas DataFrame 的一列中查找并替换所有匹配但不区分大小写的字符串

python - 查找并统计网站上单词的匹配项 - 抓取

python - 我怎样才能在 <span> </span> 使用 python splinter lib 之间获取文本