Last active
January 28, 2016 08:25
-
-
Save Kasahs/3f997927e205aebbc006 to your computer and use it in GitHub Desktop.
To generate new headers for scraping purposes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Expose methods to return new header dictionary. Supports only GET requests at the moment. | |
(Using phantomJS to throw them off. Maybe overkill. Could have used simple get request.) | |
""" | |
from selenium import webdriver | |
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities | |
# edit desired capabilities | |
dcap = dict(DesiredCapabilities.PHANTOMJS) | |
dcap["phantomjs.page.settings.userAgent"] = ( | |
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 " | |
"(KHTML, like Gecko) Chrome/15.0.87" | |
) | |
dcap['pahntomjs.page.settings.loadImages'] = False | |
driver = webdriver.PhantomJS('/home/ubuntu/.nvm/v4.2.4/bin/phantomjs', desired_capabilities=dcap) | |
def get_new_cookies(url): | |
"""Return new cookie string""" | |
try: | |
driver.delete_all_cookies() | |
driver.get(url) | |
cookies = driver.get_cookies() | |
cookie_str = ' ; '.join([c['name'] + '=' + c['value'] for c in cookies]) | |
return cookie_str | |
except Exception as e: | |
print('ERROR: failed to get new cookies. Caused by: %s ' % e.__str__()) | |
return None | |
def get_new_headers(url): | |
"""Return new header dict""" | |
cookies = get_new_cookies(url) | |
if cookies: | |
headers = { | |
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36', | |
'Cookie': cookies, | |
'Accept': '*/*', | |
'X-Requested-With': 'XMLHttpRequest' | |
} | |
else: | |
headers = None | |
return headers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment