无标题文章

···

# coding:utf-8

#

# 把qq.ip138.com/train/上面的列车时刻表抓取解析出来,输出在命令行显示,并存入一个文件train_time.text

#

import requests

import time

from bs4 import BeautifulSoup

import random

BSLIB = 'html5lib'

BASE_URL = 'http://qq.ip138.com'

UA = ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Mozilla/5.0 (X11; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"]

def get_province(province, url,file):

print(province)

file.write("%s\n" % province)

HEADERS = {'user-agent': random.choice(UA)}

r = requests.get(url, headers=HEADERS)

s = BeautifulSoup(r.text.encode(r.encoding).decode('gbk'), BSLIB)

C = s.select('div > table > tbody > tr > td > a')

for c in C: # 每个城市

get_city(c.text, BASE_URL+c.get('href'),file)

# time.sleep(random.random()*30)# 防止访问频繁,被拒绝

def get_city(city, url,file):

print('  %s' % city)

file.write("  %s\n" % city)

HEADERS = {'user-agent': random.choice(UA)}

r = requests.get(url, headers=HEADERS)

s = BeautifulSoup(r.text.encode(r.encoding).decode('gbk'), BSLIB)

T = s.select('div#checilist > table > tbody > tr')

for t in T: # 每个车次

t_text = "\t"

tt = t.select('td')

for i in tt: # 每个车次的具体每个信息用\t隔开

t_text += "%s\t" % i.text

print(t_text)

file.write('%s\n' % t_text)

# time.sleep(random.random()*4)

if __name__=='__main__':

out_file = open('train_time.txt', 'w')

url = BASE_URL+'/train/'

HEADERS = {'user-agent': random.choice(UA)}

r = requests.get(url, headers=HEADERS)

s = BeautifulSoup(r.text.encode(r.encoding).decode('gbk'), BSLIB)

P = s.select('table[width="600"] > tbody > tr > td > a')

for p in P: # 每个省份

get_province(p.text, BASE_URL+p.get('href'), out_file)

···

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,937评论 18 139
  • title: Optical Character Recognition (OCR)author: Marina ...
    4a87cc38dcbc阅读 386评论 0 0
  • # 一度蜜v3.0协议 --- # 交互协议 [TOC] ## 协议说明 ### 请求参数 下表列出了v3.0版协...
    c5e350bc5b40阅读 670评论 0 0
  • 你初来时,像红酒和蜜, 甜蜜的滋味灼烧我的口唇。 如今你像早晨的新鲜面包, 平易、可口, 我几乎没尝到你 因为我已...
    东丰林波阅读 216评论 0 0
  • 有什么事如果美好的不像真的,那肯定没那么美好。
    三宝她爹阅读 165评论 0 0