python-请求url作为移动

python-请求url作为移动,python,python-requests,urllib2,user-agent,Python,Python Requests,Urllib2,User Agent,我正试图通过User Agent将GET请求作为移动设备发送到一些url,以获取重定向的url(例如-而不是) 我已经尝试了请求库和urllib2——似乎用户代理没有随请求一起发送。也可以在这里阅读另一个问题,但答案不够清楚——是因为它有问题还是我遗漏了什么 这是我的代码: try: req = requests.get(item.url, headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS

我正试图通过
User Agent
GET
请求作为移动设备发送到一些url,以获取重定向的url(例如-而不是)

我已经尝试了
请求
库和
urllib2
——似乎
用户代理
没有随请求一起发送。也可以在这里阅读另一个问题,但答案不够清楚——是因为它有问题还是我遗漏了什么

这是我的代码:

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) + ')')

不过,还是要买电脑版而不是手机版。

嗯,最终找到了解决方案。。它有点慢,如果不需要我需要的移动版本,只需使用
urlib2
请求

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()
请注意,我使用了Chrome驱动程序-您可以在这里找到它


享受。

要作为手机进行请求,快速解决方案(非硒解决方案)使用BeautifulSoup,如下所示:

from bs4 import BeautifulSoup
import requests
headers_mobile = { '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'}
link = 'some link'
B_response = requests.get(link, headers=headers_mobile)
B_soup = BeautifulSoup(B_response.content, 'html.parser')

我不知道你为什么认为用户代理没有被发送。大多数网站——包括谷歌——不会重定向到其他移动URL,它们只是在主URL上显示正确的布局/样式表。如果不是所有的事情都是通过检测用户代理完成的呢?那么JS,cookies呢?特别是JS。检查JS Rendery你可能想使用
fiddler
charles
等工具进行调试,在请求中设置代理,然后将其与来自iPhone的实际请求进行比较,你会发现缺少了什么。@DanielRoseman因为我知道有一些网站确实存在移动版本(如果只是几个链接,我可以不用脚本,但它有数百个链接)。