无法替换useragent

问题描述 投票:0回答:1

我使用 fake_useragent 作为随机用户代理,但它仍然保留 python-requests/2.28.1

user = UserAgent()

header = {'user_agent': user.random}

link = "url"
responce = requests.get(link, headers = header).text
soup = BeautifulSoup(responce, 'lxml')
block = soup.find('div', id = 'tool_padding')

check_js = block.find('div', id = "javascript_check")
check_flash = block.find('div', id = "flash_version")
check_ua = block.find('div', id = "user_agent").text

result_js = check_js.find_all('span')[1].text
result_flash = check_flash.find_all('span')[1].text

print(f'js: {result_js}\nflash: {result_flash}\n', check_ua)

版本更新至1.5.1

python parsing user-agent
1个回答
0
投票

您在标题字典中使用了不正确的键。设置

User-Agent
的正确键是“User-Agent”(连字符 + 大写字母),而不是“user_agent”;)

  1. 更改为
    header
    headers
  2. 将“user_agent”更改为“用户代理”
  3. responce
    应该是
    response

试试这个:

from fake_useragent import UserAgent
import requests
from bs4 import BeautifulSoup

user = UserAgent()

headers = {'User-Agent': user.random}

link = "url"  # Replace with your actual URL
response = requests.get(link, headers=headers).text
soup = BeautifulSoup(response, 'lxml')
block = soup.find('div', id='tool_padding')

check_js = block.find('div', id="javascript_check")
check_flash = block.find('div', id="flash_version")
check_ua = block.find('div', id="user_agent").text

result_js = check_js.find_all('span')[1].text
result_flash = check_flash.find_all('span')[1].text

print(f'js: {result_js}\nflash: {result_flash}\n{check_ua}')

© www.soinside.com 2019 - 2024. All rights reserved.