【问题标题】:python - request url as mobilepython - 请求 url 作为移动设备
【发布时间】:2017-03-22 09:04:44
【问题描述】:

我正在尝试将GET 请求发送到一些以User-Agent 为移动设备的网址,以获取重定向的网址(例如-http://m.google.com 而不是http://google.com)。

我也尝试过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) + ')')

不过,始终获取计算机版本而不是移动版本。

【问题讨论】:

  • 我不确定您为什么认为未发送用户代理。大多数网站 - 包括 Google - 不会重定向到另一个移动 URL,它们只是在主 URL 上显示正确的布局/样式表。
  • 如果不是一切都通过检测用户代理来完成怎么办? JS,cookies怎么样?尤其是 JS。
  • 检查 out 这个 JS 渲染
  • 您可能想使用fiddlercharles 等工具进行调试,在您的请求中设置代理,然后将其与来自您的iPhone 的实际请求进行比较,您会发现缺少什么。
  • @DanielRoseman 因为有些网站我肯定知道有移动版本(如果只是几个链接,我可以不用脚本就可以做到,但它有数百个链接)。

标签: python python-requests urllib2 user-agent


【解决方案1】:

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

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 驱动程序 - 你可以在这里找到它https://sites.google.com/a/chromium.org/chromedriver/downloads

享受吧。

【讨论】:

    【解决方案2】:

    要作为手机请求,快速解决方案(非 Selenium 之一)是使用 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')
    

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2020-08-28
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多