python : BeautifulSoup 网页 table 抓取实例

python 2.7 :  编写  get_pl5.py 如下

# -*- coding: utf-8 -*-
import os,sys
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup

# 体彩 排列5
URL = "http://www.lottery.gov.cn/historykj/history.jspx?_ltype=plw"
page = urllib2.urlopen(URL)
soup = BeautifulSoup(page)
page.close()

fp = open("pl5.txt","w")
tables = soup.findAll('table')
tab = tables[0]
for tr in tab.tbody.findAll('tr'):
    for td in tr.findAll('td'):
        text = td.getText().encode('cp936')+'!'
        fp.write(text)
    fp.write('\n')
#
fp.close()

python 3.7+ : pip install beautilfulsoup4 或者  pip install bs4

# -*- coding: utf-8 -*-
import os,sys
import requests
from bs4 import BeautifulSoup
# urllib.request.urlopen
# main()
if len(sys.argv) ==2:
    n = sys.argv[1]
else:
    print('usage: get_2seq.py n ')
    sys.exit(1)

n = '5' 
# 福彩 双色球
url = "https://www.gdfc.org.cn/play_list_game_"+ n +".html"
header ={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/95.0.4638.69 "}
resp = requests.get(url, headers=header)
resp.encoding = resp.apparent_encoding
soup = BeautifulSoup(resp.text, "html.parser")
resp.close()
 
fp = open("fc2seq.txt", 'w', encoding='utf-8')
tables = soup.find_all('table')
tab = tables[0]
for tr in tab.find_all('tr')[1:]:
    for td in tr.find_all('td')[:-1]:
        dict1 = td.attrs
        txt =''
        if 'luckyno' in dict1:
            t = dict1['luckyno']
            if len(t) ==14:
                txt = ','.join((t[0:2],t[2:4],t[4:6],t[6:8],t[8:10],t[10:12]))+'!'+t[12:]
            else:
                txt = t
        else:   
            txt = td.text
        fp.write(txt+'!')
    fp.write('\n')
fp.close()

运行 python get_2seq.py 5

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值