python爬虫 爬取页面链接

本文介绍了一个简单的Python网页爬虫实例,使用BeautifulSoup和urllib库从指定网站抓取页面链接。通过Request获取网页内容,并利用BeautifulSoup解析HTML,最终遍历并打印出目标页面的所有链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
from bs4 import BeautifulSoup
import lxml  
import urllib
from urllib import request
url = 'http://ecpi.ggj.gov.cn/jndfgz/'#爬取页面


req=request.Request(url)
res=urllib.request.urlopen(req)
cont=res.read()
soup = BeautifulSoup(cont,'html.parser')  


for link in soup.center.find_all('a'):#soup.ceter.find_all中,center为选取链接的外框
    if 'href' in link.arrts:
        print (link.attrs['href'])
以下是使用Python爬虫爬取网页链接的示例代码: ```python import requests import re import threading # 定义一个获取页面源代码的函数 def get_html(url): try: response = requests.get(url) if response.status_code == 200: return response.text return None except Exception as e: print(e) return None # 定义一个获取页面中所有链接的函数 def get_links(html): pattern = re.compile('<a.*?href="(.*?)".*?>', re.S) links = re.findall(pattern, html) return links # 定义一个爬取链接的函数 def crawler(url): html = get_html(url) if html: links = get_links(html) for link in links: print(link) # 定义一个多线程爬虫函数 def multi_thread_crawler(urls): threads = [] for url in urls: t = threading.Thread(target=crawler, args=(url,)) threads.append(t) for t in threads: t.start() for t in threads: t.join() # 测试 if __name__ == '__main__': urls = ['https://www.baidu.com', 'https://www.sina.com.cn', 'https://www.qq.com'] multi_thread_crawler(urls) ``` 该示例代码中,我们使用requests库获取网页源代码,使用正则表达式获取页面中的所有链接,并使用多线程技术来提高爬虫的运行效率。我们定义了一个`get_html`函数来获取页面源代码,一个`get_links`函数来获取页面中的所有链接,一个`crawler`函数来爬取链接,最后定义了一个`multi_thread_crawler`函数来实现多线程爬虫。在测试中,我们传入了三个网址,程序会同时爬取这三个网址中的所有链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值