Python:Selenium Chrome无弹窗+property/attribute/text

我们在用Selenium写自动化程序时候,并不希望程序在实际运行过程中一直弹Chrome窗口,这个时候就需要让Chrome默默打开,自动读取数据,然后默默关闭掉就好。

  • 以下是让chrome用无界面形式打开方法,主要是chrome_options参数的设置。在使用过程中发现如果chrome浏览器版本是v60+的会不起作用,升级到v70+就可以了。
#让chrome用无界面形式打开
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver_chrome = webdriver.Chrome(chrome_options=chrome_options)
  • 针对text/get_attribute/get_property这3这的区别:
    • text是元素本身的文字内容
    • get_attribute是该元素的属性,或者说是按钮或者是栏位的title
    • get_property是文本框内输入的内容

 

代码:

from selenium import webdriver

url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=driver_chrome.close()%20driver_chrome.quit()&oq=%25E5%2586%2599%25E6%258A%2580%25E6%259C%25AF%25E6%2596%2587%25E7%25AB%25A0%25E5%258E%25BB%25E5%2593%25AA%25E9%2587%258C%25E5%25A5%25BD&rsv_pq=b7b407270017fc3f&rsv_t=b631%2B%2Fcdu8anq1OMvmgCcdPCnsCNNe%2BKKawHK4cgDCDH11XkD1wTbuFFLNc&rqlang=cn&rsv_enter=1&inputT=12858&rsv_n=2&rsv_sug3=40&bs=%E5%86%99%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0%E5%8E%BB%E5%93%AA%E9%87%8C%E5%A5%BD'

#让chrome用无界面形式打开
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver_chrome = webdriver.Chrome(chrome_options=chrome_options)

driver_chrome.get(url)

#获取text值
text_value = driver_chrome.find_element_by_xpath('''//*[@id="1"]/h3/a''').text
print('text: ' + text_value)
#获取get_attribute值
get_attribute_value = driver_chrome.find_element_by_xpath('''//*[@id="su"]''').get_attribute('value')
print('get_attribute: ' + get_attribute_value)
#获取get_property值
get_property_value = driver_chrome.find_element_by_xpath('''//*[@id="kw"]''').get_property('value')
print('get_property: ' + get_property_value)

#关闭web driver
driver_chrome.close()
driver_chrome.quit()

猜你喜欢

转载自www.cnblogs.com/danvy/p/10131725.html
今日推荐