要使用Python解析网页源代码,你可以使用`requests`库来获取网页内容,然后使用`BeautifulSoup`库来解析HTML代码。以下是使用这两个库的基本步骤:
1. 安装`requests`和`BeautifulSoup`库(如果尚未安装):
pip install requestspip install beautifulsoup4
2. 使用`requests`库获取网页内容:
import requestsurl = 'http://example.com' 替换为你想解析的网页URLresponse = requests.get(url)html_content = response.text 获取网页的文本内容
3. 使用`BeautifulSoup`库解析HTML内容:

from bs4 import BeautifulSoupsoup = BeautifulSoup(html_content, 'html.parser') 使用'html.parser'解析器
提取标题title = soup.title.stringprint(f'网页标题:{title}')提取所有链接links = soup.find_all('a')for link in links:print(f'链接文本:{link.string}, 链接地址:{link["href"]}')提取图片images = soup.find_all('img')for img in images:print(f'图片地址:{img["src"]}')
以上步骤展示了如何使用Python和BeautifulSoup库来解析网页源代码并提取信息。如果你需要更详细的解析方法,比如使用XPath或CSS选择器,可以进一步查阅BeautifulSoup的文档。
