我要收集的数据是这个网站:农产品类型和产品名称
讲在前面
这个网页一进来会有一个提示:alert("输入验证码!")
这个在selenium面前还是比较好办的,代码如下:
# 源网址
url="http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml"
driver = webdriver.Chrome()
driver.get(url) # 打开有alert弹框的HTML页面
driver.implicitly_wait(10)
# 反爬虫:进入页面需点击alert弹窗
dig_alert = driver.switch_to.alert
dig_alert.accept()
driver.implicitly_wait(10)
我使用的是chromedriver插件,如果没有装过的可以看这篇博客:chromedriver安装教程
言归正传
selenium提供了下拉框的类Select,导入如下:
from selenium.webdriver.support.ui import Select
Select类提供了三种选择的方式:索引、值、可见文本
(1)索引:select_by_index(index);index从0开始
(2)值:selec_by_value(value);value是option标签的属性值
(3)可见文本:select_by_visible_text(text);text是下拉框我们可以选择的选项文本;
对于图1的网站我们可以如下爬取:
# 获取下拉框的产品种类和索引
select_product = driver.find_element_by_name("par_craft_index")
options = select_product.find_elements_by_tag_name("option")
for option in options:
if option.text == "请选择":
continue
print(option.get_attribute("value"),option.text)
# 下拉框的一个实例化
s = Select(select_product)
# 显示的值选择
s.select_by_index(options.index(option)) # 索引
# s.select_by_value(option.get_attribute("value")) # 值
# s.select_by_visible_text(option.text) # 可见文本
# 二级下拉列表选择
sub_product = driver.find_element_by_name("craft_index")
sub_options = sub_product.find_elements_by_tag_name("option")
for sub_option in sub_options:
if sub_option.text == "请选择":
continue
print(sub_option.get_attribute("value"),sub_option.text)
print("******************************")
如果想继续了解反选、选择项的内容,可以移步https://www.cnblogs.com/z-x-y/p/9020833.html。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。