我需要用bs4获取一个select标签中被选中的option元素的value。我知道用selenium可以轻松做到 driver.find_element(By.ID, 'sex').get_attribute('value'), 但是selenium直接读取速度太慢,我的数据量庞大,所以不能用。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="content-type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<div>
<label>Info:</label>
<select title="This is an info Component" id="sex" name="sex" class="ComboBox">
<option value="">--Select--</option>
<option value="M">Male</option>
<option value="F">Female</option>
<option value="O">Others</option>
</select>
</div>
</body>
</html>
我尝试了一下,无论选了哪个option,HTML都没变化,直接分析HTML元素,我分辨不出哪个option被选中了,但是在Edge控制台上,用 document.querySelector('#sex option:checked') 可以直接返回被选中的元素。于是我参照这个方法写了下面这段代码:
from bs4 import BeautifulSoup as bs
from selenium import webdriver
wb = webdriver.Edge()
wb.get('xxxxxxxx')
soup = bs(wb.page_source, 'html.parser')
elements = soup.select('#sex option:checked')
for element in elements:
print(element)
代码可以运行,但是结果为空,并没有找到相应的option元素。
我想问通过bs4,有什么办法可以返回select标签被选中option的值吗
select标签中的option元素是页面加载时就被选中的吗
如果是页面加载之后才被选中的,需要在option元素被选中之后再获取wb.page_source并执行soup = bs(wb.page_source, 'html.parser')
另外因为bs4只是分析页面的源代码,
如果页面中是用document.getElementById("sex").value = "F";方式让option元素被选中的, 源代码中没有变化,也就没办法用bs4分析了
如果页面中是用document.getElementById("sex").options[2].setAttribute("selected","selected");方式让option元素被选中的, 源代码中才有变化,才能用bs4分析
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="content-type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<div>
<label>Info:</label>
<select title="This is an info Component" id="sex" name="sex" class="ComboBox">
<option value="">--Select--</option>
<option value="M">Male</option>
<option value="F">Female</option>
<option value="O">Others</option>
</select>
</div>
<script type="text/javascript">
setTimeout(function(){
document.getElementById("sex").options[2].setAttribute("selected","selected");
console.log(document.body.innerHTML);
}, 1000);
</script>
</body>
</html>
from bs4 import BeautifulSoup as bs
from selenium import webdriver
import time
wb = webdriver.Edge()
wb.get('file:///E:/Documents/aaa.html')
time.sleep(5)
print(wb.page_source)
soup = bs(wb.page_source, 'html.parser')
elements = soup.select('#sex option:checked')
for element in elements:
print(element)
对于用document.getElementById("sex").value = "F";方式让option元素被选中的,唯一的方法只能是用 selenium 为选中的option元素再添加上selected属性让 源代码中有变化,再用bs4分析. 但这等同直接用selenium 处理了,没有意义了.