python遍历目录下所有html文件
时间: 2023-08-30 16:09:24 浏览: 76
可以使用 Python 的 `os` 模块来遍历目录下的所有文件。例如:
```python
import os
# 获取当前目录下的所有文件
for root, dirs, files in os.walk("."):
for file in files:
# 如果文件名以 .html 结尾,就打印文件名
if file.endswith(".html"):
print(file)
```
这样就可以遍历当前目录下的所有 HTML 文件了。
注意:`os.walk()` 会递归遍历子目录,如果只想遍历当前目录,可以使用 `os.listdir()` 函数。
```python
import os
# 获取当前目录下的所有文件
files = os.listdir(".")
for file in files:
# 如果文件名以 .html 结尾,就打印文件名
if file.endswith(".html"):
print(file)
```
相关问题
python 爬取url 目录下所有文件
你可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取一个 URL 目录下的所有文件。
首先,你需要使用 requests 库来获取目录页面的 HTML 内容。然后,使用 BeautifulSoup 库来解析 HTML,找到所有链接,过滤出文件链接,然后使用 requests 库下载这些文件。
以下是一个简单的代码示例:
```python
import os
import requests
from bs4 import BeautifulSoup
url = 'http://example.com/files/'
# 获取目录页面的 HTML 内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 遍历所有链接,找到文件链接并下载
for link in soup.find_all('a'):
href = link.get('href')
if href.endswith('.pdf'): # 这里仅下载 PDF 文件,你可以根据实际情况修改
file_url = url + href
file_name = href.split('/')[-1]
response = requests.get(file_url)
with open(file_name, 'wb') as f:
f.write(response.content)
print(f'Downloaded {file_name}')
```
注意,这个代码示例仅适用于非认证目录,如果你需要认证,你需要修改 requests 库的请求头和参数等。
使用python遍历浏览器网址列表,并下载网址下的pdf
你可以使用 Python 的 requests 库和 BeautifulSoup 库来实现遍历浏览器网址列表,并下载每个网址下的 PDF。
以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 浏览器网址列表
urls = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3']
# 遍历网址列表
for url in urls:
# 发送 GET 请求
response = requests.get(url, headers=headers)
# 解析响应内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取所有的链接
links = soup.find_all('a')
# 遍历链接列表
for link in links:
# 获取链接地址
href = link.get('href')
# 如果链接是 PDF 文件
if href.endswith('.pdf'):
# 拼接 PDF 文件链接
pdf_url = url + href
# 发送 GET 请求
pdf_response = requests.get(pdf_url, headers=headers)
# 以二进制形式获取响应内容
pdf_content = pdf_response.content
# 将响应内容写入本地文件
with open(href, 'wb') as f:
f.write(pdf_content)
```
你需要将代码中的 `urls` 替换成你要遍历的浏览器网址列表,然后执行代码即可在当前目录下生成多个 PDF 文件,每个文件名是该 PDF 的文件名。