当前位置:首页 > python > 正文内容

如何用python获取一个网页的所有连接

zhangsir3年前 (2022-09-21)python363

如何用python获取一个网页的所有连接

很简单直接上代码:

# -*- coding: utf-8 -*-
'''
如何用python获取一个网页的所有连接
author:zhangsir
'''
import requests
import time
from lxml import etree
#网址
url = 'https://www.baidu.com'
#请求头
headers={
"Host": "www.baidu.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
"Cookie": "BIDUPSID=C7465C07C18C65C97A99CA9252B157C5; PSTM=1663725617; BAIDUID=C7465C07C18C65C93CEFB95934D4AD90:FG=1; BD_HOME=1; H_PS_PSSID=36558_36462_36921_37300_36885_37345_36569_37405_37261_26350_37285_22157_37231; BD_UPN=1a314753; BAIDUID_BFESS=C7465C07C18C65C93CEFB95934D4AD90:FG=1; BA_HECTOR=84al0lal2184a4ah810lo25o1hiks0j19; ZFY=2znAwD2OEqUOkcGnGOgJBJQB89SW7H2KCibOnac:ALc4:C"
}
#爬虫
a = requests.get(url=url,headers=headers)
#获取源码
b = a.text
#转成lxml需要的格式
html = etree.HTML(b)
#获取a标签的所有连接
link = html.xpath('//a/@href')
#去重
list2 = list(set(link))
#打印
print(list2)


zhangsir版权f2防采集https://mianka.xyz

扫描二维码推送至手机访问。

版权声明:本文由zhangsir or zhangmaam发布,如需转载请注明出处。

本文链接:https://www.mianka.xyz/post/31.html

标签: python
分享给朋友:

“如何用python获取一个网页的所有连接” 的相关文章

如何向python 列表中添加元素

Python添加元素有三种方法:append、extend、insertappend:向列表添加元素,添加到尾部实例:list=[“my”,“name”,“is”,“mark”,“age”,18] print(“添加前:”,list) list.append(“test”) print(“添加...

django框架的安装和创建第一个项目

安装Djangopip install -i https://pypi.douban.com/simple django创建项目django-admin startproject 项目名称例如 django-admin startproje...

pip安装三方库 国内的一些镜像站点推荐

pip 国内的一些镜像站点推荐镜像套路:使用cmd;输入命令pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名 即可开始安装。清华:https://pypi.tuna.tsinghua.edu.cn/simple 阿里云:http...

python selenium find_element_by_xpath 方法已经被弃用的解决办法

背景:在使用最新3.10.4Python版本时候,用selenium进行xpath定位元素,编译器提示:DeprecationWarning:find_element_by_xpath is deprecated. Please use find_element(by=By.XPATH, value...

python 爬虫 报错:UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0x8b in position”解决方案

发现报错“UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1:invalid start byte”,方法一:根据报错提示,错误原因有一条是这样的:“'Accept-Encodi...

python selenium 使用代理ip

代码如下:from selenium import webdriver chromeOptions = webdriver.ChromeOptions() chromeOptions.add_argument("--proxy-serv...