Python 中用于获取链接的库包括:1. BeautifulSoup;2. HtmlParser;3. lxml;4. Requests;5. Selenium。其中,BeautifulSoup、lxml 和 Requests 是常用的方法。

爬虫 Python 获取链接
获取链接是爬虫的主要任务之一。Python 中有多种用于获取链接的库,包括:
1. BeautifulSoup
BeautifulSoup 是一个流行的 HTML 解析库,可用于轻松提取页面上的链接。
立即学习“Python免费学习笔记(深入)”;
<code class="python">from bs4 import BeautifulSoup
# 创建 BeautifulSoup 对象
soup = BeautifulSoup(html, 'html.parser')
# 查找所有链接
links = soup.find_all('a')
# 遍历链接并输出文本和链接
for link in links:
print(link.text, link.get('href'))</code>2. HtmlParser
HtmlParser 是 Python 标准库中用于解析 HTML 的一个模块。
<code class="python">import html.parser
class MyHtmlParser(html.parser.HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'a':
print(dict(attrs).get('href'))
# 创建 HTMLParser 对象
parser = MyHtmlParser()
# 馈送 HTML 并处理
parser.feed(html)</code>3. lxml
lxml 是一个强大的 XML 处理库,也可用于解析 HTML。
<code class="python">from lxml import html
# 创建 lxml 树
tree = html.fromstring(html)
# 查找所有链接
links = tree.xpath('//a/@href')
# 输出链接
for link in links:
print(link)</code>4. Requests
Requests 是一个用于发送 HTTP 请求的库,还可以用于获取链接。
<code class="python">import requests
# 发送 GET 请求并获取响应
response = requests.get(url)
# 解析响应并提取链接
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
# 输出链接
for link in links:
print(link.get('href'))</code>5. Selenium
Selenium 是一种用于自动化 Web 浏览的库,也可用于获取链接。
<code class="python">from selenium import webdriver
# 创建 WebDriver
driver = webdriver.Firefox()
# 加载页面
driver.get(url)
# 查找所有链接
links = driver.find_elements_by_css_selector('a')
# 输出链接
for link in links:
print(link.get_attribute('href'))</code>以上就是爬虫python怎么获取链接的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号