爬取文档,尤其是TXT和DOCX格式的文档,可以通过Python的`urllib`和`BeautifulSoup`库来实现。以下是使用Python爬取TXT和DOCX文档的基本步骤:
爬取TXT文档
1. 导入必要的库:
```python
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import re
2. 尝试打开目标URL并读取内容:
```python
try:
textPage = urlopen('http://www.pythonscraping.com/pages/warandpeace/chapter1.txt')
except (URLError, HTTPError) as e:
print('Errors:\n')
print(e)
else:
text = str(textPage.read())
3. 使用正则表达式或其他方法处理文本内容:
```python
示例:使用正则表达式查找包含特定关键词的句子
pattern = re.compile(r'.*1805(\w|,|\s| )')
match = pattern.search(text)
if match is not None:
print(match.group())
爬取DOCX文档
1. 导入必要的库:
```python
from docx import Document
2. 读取TXT文件内容:
```python
with open('test.txt', 'r', encoding='utf-8') as f:
text = f.read()
3. 创建一个新的DOCX文档并添加文本内容:
```python
docu = Document()
docu.add_paragraph(text)
4. 保存DOCX文档:
```python
docu.save('test.docx')
请注意,对于复杂的网站,可能需要处理异步加载的内容,这时可能需要使用如`Selenium`等工具来模拟浏览器行为。
以上步骤展示了如何使用Python爬取TXT和DOCX文档的基本流程。实际操作时,请确保遵守目标网站的爬虫政策,并注意处理可能出现的异常情况。