【问题标题】:Extracting all cities in Wikipedia提取维基百科中的所有城市
【发布时间】:2014-12-26 03:19:15
【问题描述】:

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

什么都没有出现。

我的最终目标是提取列表中的所有城市,请问我该如何实现?

【问题讨论】:

  • 你的目标是什么!如果你想获得中国所有的城市,有一个更简单的方法来做到这一点

标签: python python-2.7 xpath beautifulsoup lxml


【解决方案1】:
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 表达式来改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2019-05-24
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多