爬美股吧 最終修改

先上代碼

# -*- coding:utf-8 -*-
import requests
from lxml import etree
import csv

import sys

reload(sys)
sys.setdefaultencoding('utf-8')

start_url = "http://guba.eastmoney.com/list,meigu_1.html"
headers = {
    "User-Agent": "Mozilla / 5.0(Windows NT 6.1;Win64;x64)"
                  "AppleWebKit / 537.36(KHTML, likeGecko)"
                  "Chrome / 58.0.3029.110"
                  "Safari / 537.36"
}


# def get_total_page(start_url):
#    html = requests.get(url=start_url, headers=headers).content
#    selector = etree.HTML(html)
#    sum_page = selector.xpath("http://span[@class='sumpage']/text()")
#    return sum_page


def parse_title():
    # sum_page = get_total_page(start_url)
    rows = []
    for num in range(1, 23):
        url = "http://guba.eastmoney.com/list,meigu_" + str(num) + ".html"
        html = requests.get(url=url, headers=headers).content
        selector = etree.HTML(html)
        items = selector.xpath("http://div[@id='articlelistnew']/div[position()>1 and position()<last()]")
        for item in items:
            title = item.xpath("span[@class='l3']/a/text()")[0].decode(encoding='utf-8')
            author_temp = item.xpath("span[@class='l4']/a/text()") if item.xpath("span[@class='l4']/a/text()") else [
                u'匿名網(wǎng)友']
            author = author_temp[0].decode(encoding='utf-8')
            read = item.xpath("span[@class='l1']/text()")[0]
            comment_num = item.xpath("span[@class='l2']/text()")[0]
            post_time = item.xpath("span[@class='l6']/text()")[0]
            last_update = item.xpath("span[@class='l5']/text()")[0]
            link = item.xpath("span[@class='l3']/a/@href")
            complete_link = 'http://guba.eastmoney.com' + link[0] if str(link[0]).startswith('/') else 'http://guba.eastmoney.com/' + link[0]
            rows.append(
                {'title': title, 'author': author, 'read': read, 'comment_num': comment_num, 'post_time': post_time,
                 'last_update': last_update, 'link': link, 'complete_link': complete_link})
    return rows


def parse_content_comment():
    links = []
    temp = parse_title()
    for item in temp:
        links.append(item['link'][0])
    rows = []
    for link in links[0:8]:
        url = "http://guba.eastmoney.com/" + link
        html = requests.get(url=url, headers=headers).text.decode(encoding='utf-8')
        selector = etree.HTML(html)
        lines = {}
        content = ''
        contents = selector.xpath("http://div[@class='stockcodec']/div[@id='zw_body']/p/text()") if selector.xpath("http://div[@class='stockcodec']/div[@id='zw_body']/p/text()") else [u'none']
        for item in contents:
            content += item
        lines['content'] = content
        comments = selector.xpath("http://div[@id='zwlist']")
        for item in comments:
            if item.xpath("div[@class='zwli clearfix']"):
                name = ''
                names = item.xpath("div/div/div/div[@class='zwlianame']/span/a/text()")
                for na in names:
                    name += na
                comment = ''
                comments = item.xpath("div/div/div/div[@class='zwlitext stockcodec']/text()")
                for co in comments:
                    comment += co.strip()
                time = ''
                times = item.xpath("div/div/div/div[@class='zwlitime']/text()")
                for ti in times:
                    time += ti
                lines['name'] = name
                lines['comment'] = comment
                lines['time'] = time
            else:
                lines['name'] = 'none'
                lines['comment'] = 'none'
                lines['time'] = 'none'
            rows.append(lines)
    for link in links[8:]:
        url = "http://guba.eastmoney.com" + link
        html = requests.get(url=url, headers=headers).text
        selector = etree.HTML(html)
        lines = {}
        content = ''
        contents = selector.xpath("http://div[@class='stockcodec']/text()") if selector.xpath("http://div[@class='stockcodec']/text()") else [u'none']
        for co in contents:
            content += co.strip()
        lines['content'] = content
        comments = selector.xpath("http://div[@id='zwlist']")
        for item in comments:
            if item.xpath("div[@class='zwli clearfix']"):
                name = ''
                names = item.xpath("div/div/div/div[@class='zwlianame']/span/a/text()")
                for na in names:
                    name += na
                comment = ''
                comments = item.xpath("div/div/div/div[@class='zwlitext stockcodec']/text()")
                for co in comments:
                    comment += co
                time = ''
                times = item.xpath("div/div/div/div[@class='zwlitime']/text()")
                for ti in times:
                    time += ti
                lines['name'] = name
                lines['comment'] = comment
                lines['time'] = time
            else:
                lines['name'] = 'none'
                lines['comment'] = 'none'
                lines['time'] = 'none'
            rows.append(lines)
    return rows


if __name__ == "__main__":
    headlines1 = ['title', 'author', 'read', 'comment_num', 'post_time', 'last_update', 'link', 'complete_link']
    headlines2 = ['content', 'name', 'comment', 'time']
    #    get_total_page(start_url)
    rows1 = parse_title()
    rows2 = parse_content_comment()
    with open('eastmoney1.csv', 'wb') as f:
        f_csv = csv.DictWriter(f, headlines1)
        f_csv.writeheader()
        f_csv.writerows(rows1)
    with open('eastmoney2.csv', 'wb') as f:
        f_csv = csv.DictWriter(f, headlines2)
        f_csv.writeheader()
        f_csv.writerows(rows2)

結(jié)果

之前不知道為何會(huì)亂碼,這個(gè)星期這個(gè)作業(yè)就一直在我心里糾纏著我,今天冷靜的分析了一下原因储耐,終于發(fā)現(xiàn)了問(wèn)題钝荡,別提有多開(kāi)心了街立。

問(wèn)題就出在這里
html = requests.get(url=url, headers=headers).text
html = requests.get(url=url, headers=headers).content

看源碼

    @property
    def text(self):
        """Content of the response, in unicode.

        If Response.encoding is None, encoding will be guessed using
        ``chardet``.

        The encoding of the response content is determined based solely on HTTP
        headers, following RFC 2616 to the letter. If you can take advantage of
        non-HTTP knowledge to make a better guess at the encoding, you should
        set ``r.encoding`` appropriately before accessing this property.
        """

    #content的完整代碼就不貼了。
    @property
    def content(self):
        """Content of the response, in bytes."""

.text返回的是Unicode型的數(shù)據(jù)埠通。
.content返回的是bytes型也就是二進(jìn)制的數(shù)據(jù)
之前一直用.content來(lái)解析所以一直出錯(cuò)赎离。
心頭只恨總算除掉了!又漲經(jīng)驗(yàn)了端辱!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末梁剔,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子舞蔽,更是在濱河造成了極大的恐慌荣病,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件渗柿,死亡現(xiàn)場(chǎng)離奇詭異个盆,居然都是意外死亡脖岛,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門颊亮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)柴梆,“玉大人,你說(shuō)我怎么就攤上這事终惑∩茉冢” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵雹有,是天一觀的道長(zhǎng)偿渡。 經(jīng)常有香客問(wèn)我,道長(zhǎng)霸奕,這世上最難降的妖魔是什么溜宽? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮铅祸,結(jié)果婚禮上坑质,老公的妹妹穿的比我還像新娘。我一直安慰自己临梗,他們只是感情好涡扼,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著盟庞,像睡著了一般吃沪。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上什猖,一...
    開(kāi)封第一講書(shū)人閱讀 52,255評(píng)論 1 308
  • 那天票彪,我揣著相機(jī)與錄音,去河邊找鬼不狮。 笑死降铸,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的摇零。 我是一名探鬼主播推掸,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼驻仅!你這毒婦竟也來(lái)了谅畅?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤噪服,失蹤者是張志新(化名)和其女友劉穎毡泻,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體粘优,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡仇味,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年呻顽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片邪铲。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡芬位,死狀恐怖无拗,靈堂內(nèi)的尸體忽然破棺而出带到,到底是詐尸還是另有隱情,我是刑警寧澤英染,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布揽惹,位于F島的核電站,受9級(jí)特大地震影響四康,放射性物質(zhì)發(fā)生泄漏搪搏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一闪金、第九天 我趴在偏房一處隱蔽的房頂上張望疯溺。 院中可真熱鬧,春花似錦哎垦、人聲如沸囱嫩。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)墨闲。三九已至,卻和暖如春郑口,著一層夾襖步出監(jiān)牢的瞬間鸳碧,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工犬性, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留瞻离,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓乒裆,卻偏偏與公主長(zhǎng)得像套利,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缸兔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 說(shuō)明:本文是我在readthedocs看到的日裙,覺(jué)得很不錯(cuò)所以轉(zhuǎn)載過(guò)來(lái),有刪改惰蜜,原文地址點(diǎn)這里昂拂。 實(shí)用Unicode...
    aurora閱讀 987評(píng)論 0 6
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)抛猖,斷路器格侯,智...
    卡卡羅2017閱讀 134,697評(píng)論 18 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法鼻听,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法联四,繼承相關(guān)的語(yǔ)法撑碴,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,662評(píng)論 18 399
  • 01 年初朝墩,剛上高中的小表弟醉拓,突然性情大變:不僅迷上游戲,不能自拔收苏,而且對(duì)阿姨的勸說(shuō)不理不睬亿卤,甚至惡語(yǔ)傷人。 阿姨...
    遇見(jiàn)唐姑娘閱讀 1,713評(píng)論 16 23
  • (國(guó)教 魏軍)12月16日至17日鹿霸,國(guó)教中心舉行了第四次月考排吴。開(kāi)考前,劉同華校長(zhǎng)對(duì)月考的組織及監(jiān)考做提出了相關(guān)...
    淮濱高中魏軍閱讀 318評(píng)論 0 0