python - 为什么这个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
解决方案
改用硒:
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
推荐阅读
- asp.net-core - DocuSign C# WebApi 错误:“意外的 PEM 类型”
- java - Slack Officiel SDK - 无法获取新添加的频道
- c - 这个表达式的优先级在 C 中如何工作
- c++ - 计算机器人占地面积
- javascript - 使用threejs进行图像处理
- javascript - 自 Chrome 88 以来的 SignalR 和/或计时器问题
- typescript - 在 TypeScript 中动态提取类型
- sql - 在没有内容重复的情况下在 SQL 中恢复树结构
- .htaccess - 将标头集 Access-Control-Allow-Methods 添加到 Htaccess 时出现内部服务器错误
- javafx - TableView:填充可编辑的 TextField 容器