Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added UTF-8 encoding and RandomUserAgentMiddleware #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ improve crawling speed.
Get your proxy list from sites like http://www.hidemyass.com/ (copy-paste into text file
and reformat to http://host:port format)

You can use RandomUserAgentMiddleware to have a random user agent every request the spider makes.

settings.py
-----------

Expand All @@ -20,6 +22,9 @@ settings.py
# Fix path to this module
'yourspider.randomproxy.RandomProxy': 100,
'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,
'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None,
# Disable compression middleware, so the actual HTML pages are cached
'scraper.random_user_agent.RandomUserAgentMiddleware': 400,
}

# Proxy list containing entries like
Expand All @@ -29,6 +34,15 @@ settings.py
# ...
PROXY_LIST = '/path/to/proxy/list.txt'

### More comprehensive list can be found at
### http://techpatterns.com/forums/about304.html
USER_AGENT_LIST = [
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0) Gecko/16.0 Firefox/16.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
]



Your spider
-----------
Expand Down
12 changes: 12 additions & 0 deletions randomproxy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2013 by Aivars Kalvans <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
Expand All @@ -22,6 +24,16 @@
import random
import base64
from scrapy import log
from scrapy.settings import USER_AGENT_LIST

class RandomUserAgentMiddleware(object):
def process_request(self, request, spider):
if random.choice(xrange(1,100)) <= 30:
log.msg('Changing UserAgent')
ua = random.choice(USER_AGENT_LIST)
if ua:
request.headers.setdefault('User-Agent', ua)
log.msg('>>>> UA changed to %s'%request.headers)

class RandomProxy(object):
def __init__(self, settings):
Expand Down