要使用Python抓取网页内容,你可以使用`requests`库发起HTTP请求来获取网页源代码,然后使用`BeautifulSoup`库解析HTML文档提取所需数据。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
发起请求
url = 'https://www.example.com'
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'
}
response = requests.get(url, headers=headers)
检查响应状态码
if response.status_code == 200:
获取网页内容
html_content = response.text
使用BeautifulSoup解析HTML
soup = BeautifulSoup(html_content, 'html.parser')
提取网页中的数据(这里以提取所有链接为例)
links = soup.find_all('a')
打印提取到的链接
for link in links:
print(link.get('href'))
else:
print('网页请求失败,状态码:', response.status_code)
这段代码首先使用`requests.get`方法发起一个GET请求,并传递一个`User-Agent`头以模拟浏览器访问。如果请求成功(状态码为200),则使用`BeautifulSoup`解析返回的HTML内容,并提取所有``标签中的`href`属性(即链接)。
请根据你的具体需求修改代码,比如提取特定的数据、处理分页等。