Python 陽光熱線問政平台爬蟲

2021-09-29 16:23:16 字數 4509 閱讀 2560

爬取投訴帖子的編號、帖子的url、帖子的標題,和帖子裡的內容。

import scrapy

class dongguanitem(scrapy.item):

# 每個帖子的標題

title = scrapy.field()

# 每個帖子的編號

number = scrapy.field()

# 每個帖子的文字內容

content = scrapy.field()

# 每個帖子的url

url = scrapy.field()

spider 版本

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

import scrapy

from dongguan.items import dongguanitem

class sunspider(crawlspider):

name = 'sun'

allowed_domains = ['wz.sun0769.com']

url = ''

offset = 0

start_urls = [url + str(offset)]

def parse(self, response):

# 取出每個頁面裡帖子鏈結列表

links = response.xpath("//div[@class='greyframe']/table//td/a[@class='news14']/@href").extract()

# 迭代傳送每個帖子的請求,呼叫parse_item方法處理

for link in links:

yield scrapy.request(link, callback = self.parse_item)

# 設定頁碼終止條件,並且每次傳送新的頁面請求呼叫parse方法處理

if self.offset <= 71130:

self.offset += 30

yield scrapy.request(self.url + str(self.offset), callback = self.parse)

# 處理每個帖子裡

def parse_item(self, response):

item = dongguanitem()

# 標題

item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]

# 編號

item['number'] = item['title'].split(' ')[-1].split(":")[-1]

# 文字內容,預設先取出有情況下的文字內容列表

content = response.xpath('//div[@class="contentext"]/text()').extract()

# 如果沒有內容,則取出沒有情況下的文字內容列表

if len(content) == 0:

content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()

# content為列表,通過join方法拼接為字串,並去除首尾空格

item['content'] = "".join(content).strip()

else:

item['content'] = "".join(content).strip()

# 鏈結

item['url'] = response.url

yield item

crawlspider 版本

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

import scrapy

from scrapy.linkextractors import linkextractor

from scrapy.spiders import crawlspider, rule

from dongguan.items import dongguanitem

import time

class sunspider(crawlspider):

name = 'sun'

allowed_domains = ['wz.sun0769.com']

start_urls = ['']

# 每一頁的匹配規則

pagelink = linkextractor(allow=('type=4'))

# 每個帖子的匹配規則

contentlink = linkextractor(allow=r'/html/question/\d+/\d+.shtml')

rules = [

# 本案例為特殊情況,需要呼叫deal_links方法處理每個頁面裡的鏈結

rule(pagelink, process_links = "deal_links", follow = true),

rule(contentlink, callback = 'parse_item')

]# 需要重新處理每個頁面裡的鏈結,將鏈結裡的『type&type=4?page=***』替換為『type?type=4&page=***』(或者是type&page=***?type=4』替換為『type?page=***&type=4』),否則無法傳送這個鏈結

def deal_links(self, links):

for link in links:

link.url = link.url.replace("?","&").replace("type&", "type?")

print link.url

return links

def parse_item(self, response):

print response.url

item = dongguanitem()

# 標題

item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]

# 編號

item['number'] = item['title'].split(' ')[-1].split(":")[-1]

# 文字內容,預設先取出有情況下的文字內容列表

content = response.xpath('//div[@class="contentext"]/text()').extract()

# 如果沒有內容,則取出沒有情況下的文字內容列表

if len(content) == 0:

content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()

# content為列表,通過join方法拼接為字串,並去除首尾空格

item['content'] = "".join(content).strip()

else:

item['content'] = "".join(content).strip()

# 鏈結

item['url'] = response.url

yield item

pipelines.py

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

# 檔案處理類庫,可以指定編碼格式

import codecs

import json

class jsonwriterpipeline(object):

def __init__(self):

# 建立乙個只寫檔案,指定文字編碼格式為utf-8

self.filename = codecs.open('sunwz.json', 'w', encoding='utf-8')

def process_item(self, item, spider):

content = json.dumps(dict(item), ensure_ascii=false) + "\n"

self.filename.write(content)

return item

def spider_closed(self, spider):

self.file.close()

settings.py

item_pipelines = 

# 日誌檔名和處理等級

log_file = "dg.log"

log_level = "debug"

在專案根目錄下新建main.py檔案,用於除錯

from scrapy import cmdline

cmdline.execute('scrapy crawl sunwz'.split())

執行程式

py2 main.py

python爬取陽光電影儲存mysql

import requests from lxml import etree import re import pymysql 定義url headers 連線資料庫 db pymysql.connect host 127.0.0.1 port 3306,user root password 123...

python中的ensure ascii問題

在使用json.dumps時要注意乙個問題 import json print json.dumps 中國 u4e2d u56fd 輸出的會是 中國 中的ascii 字元碼,而不是真正的中文。這是因為json.dumps 序列化時對中文預設使用的ascii編碼.想輸出真正的中文需要指定ensure ...

python入門靈魂5問

對於剛接觸python程式設計或者想學習python自動化的人來說,基本都會有以下python入門靈魂5問 python學習路線,python教程,python學哪些,python怎麼學,python學到什麼程度?需要學習哪些內容才能征服python這條蟒蛇呢?前言 python分為2.x和3.x之...