【问题标题】:Why is this url not opening using python but can be opened directly from browser?为什么这个url不能用python打开,而是可以直接从浏览器打开?
【发布时间】:2020-02-24 09:09:09
【问题描述】:

这是我在 python 中编写的用于打开 url 的代码。

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import time
import requests
from random import randint
import urllib.parse

class AmazonReviews():
    def __init__(self):
           self.headers = {'User-Agent' : 'Mozilla/5.0'}

    def open_url(self,url):
        values = {}
        data = urllib.parse.urlencode(values).encode('utf-8')
        req = urllib.request.Request(url, data, self.headers)
        response = urllib.request.urlopen(req)
        html = response.read()
        return html

   def fetch_reviews(self,all_reviews_link):
        try:
            url = "https://www.amazon.in" + all_reviews_link
            print(url)
            html = self.open_url(url)
        except HTTPError as e:
            print(e)

review = AmazonReviews()
review.fetch_reviews('/gp/profile/amzn1.account.AFBWOEM2CWLC7ZRQ7WK6FQYXH6AA/ref=cm_cr_arp_d_gw_btm?ie=UTF8')

我这样传递 url 是因为在主项目中,这个 url 是使用提供相对路径的 href 属性来抓取的。 如果有任何获取绝对网址的方法,请提出建议。

输出 -

https://www.amazon.in/gp/profile/amzn1.account.AFBWOEM2CWLC7ZRQ7WK6FQYXH6AA/ref=cm_cr_arp_d_gw_btm?ie=UTF8
HTTP Error 404: NotFound

代码链接 https://onlinegdb.com/SyFPXzWVI

【问题讨论】:

  • 有趣的是,requests.get(url, headers=self.headers).status_code 是 403。

标签: python web-scraping beautifulsoup urllib


【解决方案1】:

改用Selenium

from selenium import webdriver
import os

browser = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd()) + "/chromedriver")
link = "https://www.amazon.in/gp/profile/amzn1.account.AFBWOEM2CWLC7ZRQ7WK6FQYXH6AA/ref=cm_cr_arp_d_gw_btm?ie=UTF8"
browser.get(link)
name = browser.find_element_by_xpath('//*[@id="customer-profile-name-header"]/div[2]/span').text

输出:

Dheeraj Malhotra

【讨论】:

  • 感谢他的解决方案。我使用类似的代码来获取此 url,它有效 /gp/profile/amzn1.account.AFBWOEM2CWLC7ZRQ7WK6FQYXH6AA/ref=cm_cr_arp_d_gw_btm?ie=UTF8' 为什么它不适用于这种情况? @Zaraki Kenpachi
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
相关资源
最近更新 更多