作者iPhone007 (iPhone007)
看板Python
标题Re: [问题] 用requests.post爬虫 以及编码的问题
时间Sat Jul 2 00:18:55 2016
用以下的方法硬解,虽然方法不是很好,不过似乎是可以解出资料
看是不是能抛砖引玉,请其他大大提出好的解法
input_year = '105'
input_month = '06'
import requests
url='
http://www.twse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php'
payload = {
'myear':input_year,
'mmon':input_month
}
res = requests.post(url, data = payload)
from bs4 import BeautifulSoup
res.encoding = 'big5'
idx_bgn = res.text.index(u"<div align=center class=til_2>")
idx_end = res.text.index(u"<!------ end of 交易资讯 > 指数资料 >加权股价指数历
史资料 --->")
html_text = res.text[idx_bgn:idx_end]
soup = BeautifulSoup(html_text)
table_board_trad = soup.select('table')[1]
trCount = 0;
for tr in table_board_trad.select('tr'):
if(trCount>1):
print tr.select('td')[0].text + ' ' +tr.select('td')[1].text
trCount = trCount + 1
※ 引述《akpipnlge (akpipnlge)》之铭言:
: 小弟因为专题需要爬证交所网站的一些资料,所以用python 2.7 和requests套件操作
: 网址如下:
: http://www.twse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php
: (每个月份都要爬)
: 程式码如下:
: import requests
: payload = {
: 'myear': 2016,
: 'mmom': 5
: }
: url='http://www.twse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php'
: page = requests.post(url, data=payload)
: print page.text.decode('iso-8859-1').encode('utf8')
: 然後就遇到两个问题:
: 1.有抓到东西,但是只有抓到其他不重要的,数据的部分完全没有
: (应该是payload那有错,抱歉小弟连html都没写过QQ)
: 2.抓下来的编码是乱码,所以加了爬文看到的解码那行,却出现error:
: UnicodeEncodeError: 'ascii' codec can't encode character u'\xbb' in position
: 130: ordinal not in range(128)
: 整整花了3个半天还是搞不定,只好PO文求救了QQ
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 223.26.109.76
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1467389938.A.1FC.html
※ 编辑: iPhone007 (223.26.109.76), 07/02/2016 00:23:38
1F:→ akpipnlge: 因为我只是要取数据而已,只要去tag就好 07/02 06:38
2F:→ akpipnlge: 所以beautifulsoup虽然不过,但是其他套件可以 07/02 06:40
3F:→ akpipnlge: 一个不求甚解XDDD 07/02 06:40
4F:→ s860134: 用 lxml 应该可以很好的爬出 tag 结构 07/02 11:18
5F:→ iPhone007: 感谢分享 ^_^ 07/02 12:01