• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
作死-no1
博客园    首页    新随笔    联系   管理    订阅  订阅

爬虫-----爬取所有国家的首都、面积 ,并保存到txt文件中

# -*- coding:utf-8 -*-

import urllib2
import lxml.html
from lxml import etree

def main():
file = open('./countrys.txt', 'w+')
file.close()
countrys = []
url = 'https://guojiadiqu.51240.com/'
html = urllib2.urlopen(url).read()
# tree = lxml.html.fromstring(html)
# td = tree.cssselect('div#main_content > ul.list > li > a > @href')[0]
selector = etree.HTML(html)
uls = selector.xpath('//div[@id="main_content"]/ul')
for ul in uls:
lis = ul.xpath('./li')
for li in lis:
country_infos = {}
key = li.xpath('./a/text()')[0]
value = 'https://guojiadiqu.51240.com' + li.xpath('./a/@href')[0].strip()
country_infos[key] = value
countrys.append(country_infos)
return get_capital(countrys)

def get_capital(list):
i = 0
for country in list:
i += 1
name = country.keys()[0]
url = country.values()[0]
html = urllib2.urlopen(url).read()
tree = etree.HTML(html)
tr = tree.xpath('//div[@id="main_content"]/table')[0]
tr1 = tr.xpath('./tr/td/table/tr')
tr2 = tr1[2].xpath('./td/text()')
file = open('./countrys.txt', 'a')
if len(tr2) > 0:
content = str(i) + ' ' + name + '\n ' + tr2[0] + '\n'
else:
content = str(i) + ' ' + name + '\n' + ' \n'
file.write(content.encode('utf-8'))
file.close()

if __name__ == "__main__":
main()
posted @ 2018-10-02 15:46  作死-no1  阅读(346)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3