python爬虫中使用soup.findall函数如何爬取没有这个子标签的东西
时间: 2024-03-19 17:43:35 浏览: 13
使用BeautifulSoup中的find_all函数可以爬取没有某个子标签的元素。通过在CSS选择器中使用":not"伪类和子选择器">",可以实现筛选没有某个子标签的元素。以下是一个示例代码,用于爬取没有"img"子标签的"div"标签:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
divs_without_img = soup.find_all('div:not(:has(img))')
for div in divs_without_img:
print(div)
```
在上面的代码中,我们首先发送一个HTTP请求获取网页内容,然后使用BeautifulSoup解析HTML文档。接着,使用find_all函数结合":not"伪类和子选择器">",查找没有"img"子标签的"div"标签元素,并将它们保存在divs_without_img变量中。最后,我们可以遍历divs_without_img变量,并打印每个"div"元素的内容。
相关问题
python中.find函数的使用方法及实例_python 如何使用find和find_all爬虫、找文本的实现...
Python中的字符串对象有一个名为`find()`的方法,它可以用来查找字符串中的指定子字符串,并返回找到的位置。它的基本语法如下:
```
str.find(sub[, start[, end]])
```
其中,`str`是要查找的字符串,`sub`是要查找的子字符串。`start`和`end`是可选参数,用于指定查找范围的起始和结束位置。如果找到了子字符串,返回它在字符串中的下标;如果没有找到,返回-1。
以下是一个使用`find()`方法的例子,它查找字符串中第一次出现子字符串的位置:
```python
str = "hello world"
index = str.find("world")
print(index)
```
输出结果为:`6`,因为"world"子字符串在字符串中的位置是从下标6开始的。
另外,如果要查找字符串中所有出现指定子字符串的位置,可以使用`find_all()`方法,它的语法如下:
```python
str.find_all(sub[, start[, end]])
```
这个方法返回一个列表,列表中包含了所有找到的子字符串的下标。以下是一个使用`find_all()`方法的例子:
```python
str = "hello world"
indexes = [i for i in range(len(str)) if str.startswith("l", i)]
print(indexes)
```
输出结果为:`[2, 3, 9]`,因为"l"子字符串在字符串中的位置是从下标2、3、9开始的。
在爬虫和文本处理中,`find()`和`find_all()`方法经常被用来查找指定的文本或标签。例如,在使用BeautifulSoup库解析HTML文档时,可以使用`find_all()`方法查找所有的指定标签,例如:
```python
from bs4 import BeautifulSoup
import requests
url = "http://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
links = soup.find_all("a")
for link in links:
print(link.get("href"))
```
这段代码会爬取指定的网页,然后使用BeautifulSoup库解析HTML文档,最后查找所有的a标签,并打印它们的链接地址。
python爬虫爬取CNNVD网页数据,并将信息存入一个文件中
好的,这个问题我可以回答。你可以通过以下步骤来实现:
1. 导入必要的库,包括 requests 和 BeautifulSoup 等:
```python
import requests
from bs4 import BeautifulSoup
```
2. 定义一个函数用于获取网页的HTML内容:
```python
def get_html(url):
response = requests.get(url)
return response.text
```
3. 定义一个函数用于解析HTML内容:
```python
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table', class_='tlist')
rows = table.find_all('tr')[1:]
data = []
for row in rows:
cols = row.find_all('td')
vul_id = cols[0].text.strip()
vul_name = cols[1].text.strip()
vul_level = cols[2].text.strip()
vul_time = cols[3].text.strip()
data.append((vul_id, vul_name, vul_level, vul_time))
return data
```
4. 定义一个函数用于将数据存入文件:
```python
def save_to_file(data, filename):
with open(filename, 'w', encoding='utf-8') as f:
for item in data:
f.write('\t'.join(item) + '\n')
```
5. 调用函数获取数据并存入文件:
```python
if __name__ == '__main__':
url = 'http://www.cnnvd.org.cn/web/vulnerability/querylist.tag'
html = get_html(url)
data = parse_html(html)
save_to_file(data, 'cnnvd.txt')
```
这样,你就可以通过 Python 爬虫爬取CNNVD网页数据,并将信息存入一个文件中了。