Skip to main content
 首页 » 编程设计

python之提取维基百科中的所有城市

2025年05月04日8xiaohuochai

http://en.wikipedia.org/wiki/List_of_cities_in_China

我想提取所有城市名称,如下所示:

我使用以下代码(仅提取一个字段),其中 xpath 是从 chrome 复制的

from lxml import html 
import requests 
 
page = requests.get('http://en.wikipedia.org/wiki/List_of_cities_in_China') 
tree = html.fromstring(page.text) 
 
huabeiTree=tree.xpath('//*[@id="mw-content-text"]/table[3]/tbody/tr[1]/td[1]/a/text()') 
print huabeiTree 

什么都没有出现。

我的最终目标是提取列表中的所有城市,我可以知道如何实现吗?

请您参考如下方法:

from lxml import html 
import requests 
 
page = requests.get('http://en.wikipedia.org/wiki/List_of_cities_in_China') 
tree = html.fromstring(page.text) 
 
huabeiTree=tree.xpath('//table[@class="wikitable sortable"]') 
list_of_cities_table = huabeiTree[0] # table[0] is what we need 
 
# Iterate over the table, get all the <tr> nodes 
#then get the values of cities with tr[0][0].text 
for tr in list_of_cities_table: 
    if tr[0].tag == 'td': 
        print tr[0][0].text 

它打印了一个包含 656 个城市的列表,从北京到诸暨。

附言也许这不是那么优雅。可以使用更好的 Xpath 表达式进行改进。