2017-03-22 5 views
2

ように私は( - http://m.google.com代わりにhttp://google.com例えば)リダイレクトされたURLを取得するために、モバイルなどUser-AgentでいくつかのURLへのGETリクエストを送信しようとしています。のpython - 要求URLモバイル

requestsライブラリとurllib2も試しました。User-Agentはリクエストと一緒に送信されていないようです。ここで別の質問を読むこともできますが、その答えは十分ではありませんでした。

これは私のコードです:それでも

try: 
    req = requests.get(item.url, headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1'}, timeout=5) 

except requests.exceptions.HTTPError: 
    continue 

except requests.exceptions.Timeout: 
    continue 

print (item.url + ' => ' + req.url + ' (' + str(req.status_code) + ')') 

、代わりに常にモバイル版のコンピュータのバージョンを取得します。

+0

あなたがなぜユーザーエージェントが送信されていないと思うか分かりません。 Googleを含むほとんどのウェブサイトは、携帯用の別のURLにリダイレクトしないため、メインURLに正しいレイアウト/スタイルシートが表示されます。 –

+1

user-agentを検出してすべてが完了していない場合はどうなりますか? JS、クッキーはいかがですか?特にJS。 – leovp

+0

JSアウトプットの[out](https://github.com/scrapy-plugins/scrapy-splash)を確認してください –

答えて

1

まあ、最終的に解決策を見つけました。少し遅く、私が必要としていたモバイル版が不要な場合は、urllib2またはrequestsを使用してください。あなたがここにhttps://sites.google.com/a/chromium.org/chromedriver/downloads

それを見つける楽しむことができる - 私はクロームのドライバを使用

import requests 
import os 

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options as SeleniumOptions 
from selenium.common.exceptions import ErrorInResponseException, TimeoutException, UnexpectedAlertPresentException 

headers = SeleniumOptions() 
headers.add_argument("user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1") 

driver = webdriver.Chrome(executable_path=os.path.abspath('app/static/drivers/chromedriver'), chrome_options=headers) # path of the chrome driver 
driver.set_page_load_timeout(10) # request timeout - 10 seconds 

try: 
    req = driver.get(YOUR_URL_HERE) 

    print YOUR_URL_HERE + ' => ' + driver.current_url + ' (' + str(requests.get(driver.current_url).status_code) + ')' 

except ErrorInResponseException: 
    continue 

except TimeoutException: 
    continue 

except UnexpectedAlertPresentException: # dismiss alerts 
    alert = driver.switch_to.alert 
    alert.dismiss() # can be alert.accept() if you want to accept the alert 

driver.quit() 

注意。