首页 > 解决方案 > 为什么这个url不能用python打开,而是可以直接从浏览器打开?

问题描述

这是我在 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

标签: pythonweb-scrapingbeautifulsoupurllib

解决方案


改用

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

推荐阅读