python爬取静态网页数据
时间: 2025-02-20 09:20:41 浏览: 52
### 如何使用 Python 爬取静态网页的数据
#### 使用 `requests` 和 `BeautifulSoup`
对于爬取静态网页的内容,可以采用 Python 的 `requests` 库来获取网页内容,并利用 `BeautifulSoup` 来解析 HTML 并提取所需数据[^1]。
```python
import requests
from bs4 import BeautifulSoup
def fetch_web_content(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
print(f"Failed to retrieve data: {response.status_code}")
return None
except Exception as e:
print(f"Error occurred while fetching the web content: {e}")
return None
def parse_html(html_doc):
soup = BeautifulSoup(html_doc, 'html.parser')
# 假设要抓取所有的链接作为例子
links = []
for link in soup.find_all('a'):
href = link.get('href')
text = link.string
if href and text:
links.append((text.strip(), href))
return links
if __name__ == "__main__":
url = "http://example.com"
html_content = fetch_web_content(url)
if html_content is not None:
parsed_links = parse_html(html_content)
for title, link in parsed_links[:5]: # 只打印前五个链接作为示例
print(f"{title}: {link}")
```
这段代码展示了如何通过发送 HTTP 请求获得目标页面的源码字符串形式返回值;接着创建了一个新的 `BeautifulSoup` 对象用于处理这些原始文档。最后遍历所有 `<a>` 标签找到其中包含的有效超链接及其对应的显示文字。
#### 利用 `urllib.request`
另一种方式则是直接调用 `urllib.request` 中的 `urlopen()` 方法访问指定 URL 地址所指向资源,并将其转换成可读格式以便进一步操作[^2]。
```python
import urllib.request
url = 'http://www.example.com'
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
print(html) # 输出整个HTML结构体至控制台窗口内查看
```
上述实例说明了怎样打开一个特定网址连接并读取出其完整的 HTML 结构体,之后可以根据实际需求对这个字符串做更多自定义的操作,比如正则表达式的匹配查找等。
阅读全文
相关推荐


















