Skip to content

Allow USER_AGENT_LIST to be list or function #12

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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: 10 additions & 4 deletions random_useragent.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,22 @@ class RandomUserAgentMiddleware(UserAgentMiddleware):
def __init__(self, settings, user_agent='Scrapy'):
super(RandomUserAgentMiddleware, self).__init__()
self.user_agent = user_agent
user_agent_list_file = settings.get('USER_AGENT_LIST')
if not user_agent_list_file:
user_agent_list_source = settings.get('USER_AGENT_LIST')
if not user_agent_list_source:
# If USER_AGENT_LIST_FILE settings is not set,
# Use the default USER_AGENT or whatever was
# passed to the middleware.
ua = settings.get('USER_AGENT', user_agent)
self.user_agent_list = [ua]
else:
with open(user_agent_list_file, 'r') as f:
self.user_agent_list = [line.strip() for line in f.readlines()]
if any(isinstance(user_agent_list_source, t) for t in [list, tuple]):
self.user_agent_list = user_agent_list_source
elif callable(user_agent_list_source):
self.user_agent_list = user_agent_list_source()
else:
with open(user_agent_list_source, 'r') as f:
self.user_agent_list = [line.strip()
for line in f.readlines()]

@classmethod
def from_crawler(cls, crawler):
Expand Down