部分内容无法显示:
出现这种情况可能是浏览器对爬虫进行拦截,可以为webdriver添加浏览器设置。文章来源:https://www.toymoban.com/news/detail-733055.html
# 进入浏览器设置
options = webdriver.ChromeOptions()
# 设置中文
options.add_argument('lang=zh_CN.UTF-8')
# 更换头部
options.add_argument('user-agent="Mozilla/5.0 (iPod; U; CPU iPhone OS 2_1 like Mac OS X; ja-jp) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20"')
driver = webdriver.Chrome("../driver/chromedriver", chrome_options=options)
添加浏览器设置后成功显示文本内容:
完整测试代码:文章来源地址https://www.toymoban.com/news/detail-733055.html
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# 进入浏览器设置
options = webdriver.ChromeOptions()
# 设置中文
options.add_argument('lang=zh_CN.UTF-8')
# 更换头部
options.add_argument('user-agent="Mozilla/5.0 (iPod; U; CPU iPhone OS 2_1 like Mac OS X; ja-jp) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20"')
#get直接返回,不再等待界面加载完成
desired_capabilities = DesiredCapabilities.CHROME
desired_capabilities["pageLoadStrategy"] = "none"
driver = webdriver.Chrome("../driver/chromedriver", chrome_options=options)
driver.implicitly_wait(10)
url = "https://cm.bing.com"
driver.get(url)
keyword = driver.find_element(By.XPATH, "//input[@id='sb_form_q']")
keyword.send_keys("xpath")
keyword.send_keys(Keys.ENTER)
items = driver.find_elements(By.XPATH, "//li[@class='b_algo']")
for item in items:
a = item.find_element(By.TAG_NAME, "a")
print(a.get_attribute("href"))
print(a.text)
driver.quit()
到了这里,关于记录Selenium Python访问浏览器时部分内容无法获取的解决方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!