您的位置:首页 > 编程语言 > Python开发

Scrapy抓取网页相关问题解决以及注意事项总结

2016-11-04 17:56 393 查看
1、urllib2是python自带的模块,在python3.x中被改为urllib.request,如<span style="font-size:12px;">url = "http://music.baidu.com/album/all?order=time&style=pop" 

html = urllib.request.urlopen(url).read() </span> 

AttributeError: 'module' object has no attribute
'urlopen'

Python3中使用 urllib.request解决

2、can't use a string pattern on a bytes-like object

  3.0现在的参数更改了,现在读取的是bytes-like的,但参数要求是chart-like的,故定义pattern的时候在前面加一个小b,表示要操作的对象是bytes类型就可以了,如  url = "http://music.baidu.com/album/all?order=time&style=pop" html = urllib.request.urlopen(url).read()

uri = re.findall(b'/song/d+',html,re.M)  

s.encode(encoding) -> bytes

b.decode(encoding) -> str

bytes 就是一堆字节,str 是字符串;你把字符串按某种编码编码之后就成了一堆字节,正确地解码后就成了字符串。

eg1:

# apps.append(apk.split(":")[-1].split("=")[0])报错:TypeError: 'str' does not support the buffer interface

按照下面做一个转换,就fix了

s=apk.decode("GBK").split(":")[-1].split("=")[0]

apps.append(s)

eg2:

 out = shell("dumpsys window w | %s \/ | %s name=" %(find_util, find_util)).stdout.read()

return pattern.findall(out)[0]

报错:can't use a string pattern on a bytes-like object

按照下面做一个转换,就fix了

 out = shell("dumpsys window w | %s \/ | %s name=" %(find_util,find_util)).stdout.read().decode("GBK")

text = urllib.request.urlopen(url).read().decode("GBK")   #后面加上.decode("GBK") 解决

3.使用python中html.unescape()方法就可以输出html中的实体字符

&#加上十进制码,Unicode十进制码转换为中文的显示方法。

Python3.5 Unicode十进制码转换为中文解决方法如下:

#!/usr/bin/env python

# encoding: utf-8

"""

出  关①   徐兰

凭山俯海古边州, 旆②影风翻见戍楼。

马后桃花马前雪,出关争得不回头?

[注]①关,指居庸关。②旆(pèi),旌旗。

"""
import html

string = '[注]①关,指居庸关。②旆(pèi),旌旗。'

print(html.unescape(string))    #[注]①关,指居庸关。②旆(pèi),旌旗。

如果Python3中显示 no have html module 则需要pip install html 安装html模块

相关参考资料:
http://www.crifan.com/python_decode_html_entity_and_convert_between_name_entity_and_code_point_entity/
Python3.3解决方法:http://bbs.csdn.net/topics/390345154

Java实现的转换方法:http://bbs.csdn.net/topics/350123955
其他Unicode转中文解决方法:http://blog.csdn.net/shanliangliuxing/article/details/8638371

4.Scrapy爬取相对链接和绝对链接问题:示例中抓取的url是相对链接,在第7行中用urljoin转换为完整的链接。

class StackOverflowSpider(scrapy.Spider):

name = 'stackoverflow'

start_urls = ['http://stackoverflow.com/questions?sort=votes']

def parse(self, response):

    for href in response.css('.question-summary h3 a::attr(href)'):

        full_url = response.urljoin(href.extract())

        yield scrapy.Request(full_url, callback=self.parse_question)

def parse_question(self, response):

    yield {

        'title': response.css('h1 a::text').extract()[0],

        'votes': response.css('.question .vote-count-post::text').extract()[0],

        'body': response.css('.question .post-text').extract()[0],

        'tags': response.css('.question .post-tag::text').extract(),

        'link': response.url,

    }

5.python 中列表、元组、字符串相互之间的转换问题

  Python中有三个内建函数:列表,元组和字符串,他们之间的互相转换使用三个函数,str(),tuple()和list(),具体示例如下所示:

>>> s = "xxxxx"

>>> list(s)

['x', 'x', 'x', 'x', 'x']

>>> tuple(s)

('x', 'x', 'x', 'x', 'x')

>>> tuple(list(s))

('x', 'x', 'x', 'x', 'x')

>>> list(tuple(s))

['x', 'x', 'x', 'x', 'x']
列表和元组转换为字符串则必须依靠join函数
>>> "".join(tuple(s))

'xxxxx'

>>> "".join(list(s))

'xxxxx'

>>> str(tuple(s))

"('x', 'x', 'x', 'x', 'x')"

>>> 
6.Scrapy中用cookie模拟登陆新浪微博:
http://blog.csdn.net/gloria2799/article/details/46955561
抓取天猫价格数据加上headers方法:http://blog.csdn.net/xu470438000/article/details/42391929

发送带cookie请求的方法:

import sys

from scrapy.spider import Spider

from scrapy.selector import Selector

from scrapy.http.request import Request

class InfoqSpider(Spider):

    name = "techbrood"

    allowed_domains = ["techbrood.com"]

    start_urls = [

        "http://techbrood.com",

    ]

        

    def start_requests(self):

        for url in self.start_urls:        

            yield Request(url, cookies={'techbrood.com': 'true'})

7.分别用python2和python3伪装浏览器爬取网页内容

python网页抓取功能非常强大,使用urllib或者urllib2可以很轻松的抓取网页内容。但是很多时候我们要注意,可能很多网站都设置了防采集功能,不是那么轻松就能抓取到想要的内容。

python2和python3中都是如何来模拟浏览器来跳过屏蔽进行抓取的:

最基础的抓取:

#! /usr/bin/env python

# -*- coding=utf-8 -*-

# @Author pythontab

import urllib.request

url = "http://www.pythontab.com"

html = urllib.request.urlopen(url).read()

print(html)

但是...有些网站不能抓取,进行了防采集设置,所以我们要变换一下方法

python2中(最新稳定版本python2.7)

#! /usr/bin/env python

# -*- coding=utf-8 -*-

# @Author pythontab.com

import urllib2

url="http://pythontab.com"
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',

             'Accept':'text/html;q=0.9,*/*;q=0.8',

             'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',

             'Accept-Encoding':'gzip',

             'Connection':'close',

             'Referer':None #注意如果依然不能抓取的话,这里可以设置抓取网站的host

             }

req_timeout = 5

req = urllib2.Request(url,None,req_header)

resp = urllib2.urlopen(req,None,req_timeout)

html = resp.read()

print(html)

python3中(最新稳定版本python3.3)

#! /usr/bin/env python

# -*- coding=utf-8 -*-

# @Author pythontab

import urllib.request

url = "http://www.pythontab.com"

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',

             'Accept':'text/html;q=0.9,*/*;q=0.8',

             'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',

             'Accept-Encoding':'gzip',

             'Connection':'close',

             'Referer':None #注意如果依然不能抓取,这里可以设置抓取网站的host

             }

opener = urllib.request.build_opener()

opener.addheaders = [headers]

data = opener.open(url).read()

print(data)

8.匹配网页中指定位置的内容用括号括起来

p2=re.compile('<td class="val">(.*?)</td><td class="err"></td></tr>',re.M)

正则表达式完整用法
http://blog.csdn.net/wj494224911/article/details/52214601
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python scrapy 异常
相关文章推荐