如何使用python获得表标记1和表标记2之后的所有<li>?

2024-09-28 16:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想从这个网站解析或报废数据。你知道吗

http://mis.pamsimas.org/2014/result_table.php?apl=undefined&thn=2014&type=REG|ALL&dan=ALL&mod=2.1.2.1|Pemetaan%20Sosial|t_imas_peta_sosial|des||t_2121_peta_sosial&leve=&grop=

我的问题是该网站如何只获取从“18努沙登加拉帖木儿”到“145萨布赖华”的数据

谢谢你的回复,我试着用查找所有和其他,但我弄错了。你知道吗

import bs4
import request

html = request.get(link)
soup = bs4.BeautifulSoup(html,"html.parser")
        soup.prettify()
        ul = soup.find("ul", id="sitemap")
        for li in ul.find_all('table'):
            if "Jawa Timur" in li.text.strip():
                print(li.nextSibling())

Tags: 数据inimport网站requesthtmltableli
1条回答
网友
1楼 · 发布于 2024-09-28 16:22:55

我不知道你想要什么格式的输出。最初,您可以只选择相关的表,如下所示。需要bs4 4.7.1+as使用:contains和:has进行筛选。你知道吗

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

r = requests.get('http://mis.pamsimas.org/2014/result_table.php?apl=undefined&thn=2014&type=REG|ALL&dan=ALL&mod=2.1.2.1|Pemetaan%20Sosial|t_imas_peta_sosial|des||t_2121_peta_sosial&leve=&grop=')
soup = bs(r.content, 'lxml')

for table in soup.select('table:has(th:contains("Nusa Tenggara Timur")), table:has(th:contains("Nusa Tenggara Timur")) ~ li:not(table:has(th:contains("Kalimantan Barat")) ~ li)'):
    print(pd.read_html(str(table)))

如果您希望输出类似于您在评论中的图像,那么请使用以下命令(您需要使用测向列)你知道吗

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

r = requests.get('http://mis.pamsimas.org/2014/result_table.php?apl=undefined&thn=2014&type=REG|ALL&dan=ALL&mod=2.1.2.1|Pemetaan%20Sosial|t_imas_peta_sosial|des||t_2121_peta_sosial&leve=&grop=')
soup = bs(r.content, 'lxml')
trs = soup.select('tr:contains("Nasional"), table:has(th:contains("Nusa Tenggara Timur")) tr, table:has(th:contains("Nusa Tenggara Timur")) ~ li:not(table:has(th:contains("Kalimantan Barat")) ~ li) tr')
results = []

for tr in trs:
    row = [i.text.replace('\xa0 ','') if i.img is None else 'tick' for i in tr.select('th,td:not([title])')]
    if len(row) > 15:
        row = row[1:-1]
    results.append(row)
df = pd.DataFrame(results)
print(df)
df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8-sig',index = False )

我已经用输出中的单词tick替换了ticks的图像。输出示例(某些行隐藏):

enter image description here


阅读:

  1. CSS selectors

相关问题 更多 >