使用 fake_user 代理,元素未导入

问题描述

这是在 Google 搜索中编写的简单抓取代码

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(r'c:\chromedriver\chromedriver.exe',options=options)
url = f'https://www.google.com/search?q=ipad+"apple"+intext:apple&hl=en&rlz=&start=10'
driver.get(url)
items = driver.find_elements_by_xpath('//*[@id="search"]/div/div/div')
title = driver.find_elements_by_xpath('//*[@id="search"]/div/div/div/div/div/div/a/h3')

print(len(items))
print(len(title))

for item in items:
    title = item.find_element_by_xpath('.//div/div/div/a/h3').text
    print(title)

输出,有效

enter image description here

添加 fake_user 代理如下,

from selenium import webdriver
from fake_useragent import UserAgent

options = webdriver.ChromeOptions()
options.add_argument('headless')
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')

driver = webdriver.Chrome(r'c:\chromedriver\chromedriver.exe',options=options)
url = f'https://www.google.com/search?q=ipad+"apple"+intext:apple&hl=en&rlz=&start=10'
driver.get(url)
items = driver.find_elements_by_xpath('//*[@id="search"]/div/div/div')
title = driver.find_elements_by_xpath('//*[@id="search"]/div/div/div/div/div/div/a/h3')

print(len(items))
print(len(title))

for item in items:
    title = item.find_element_by_xpath('.//div/div/div/a/h3').text
    print(title)

输出

enter image description here

添加 fake_user 代理代码后,为什么我不能从相同的代码中得到结果?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)