from urllib.parse import urljoin from lxml import etree import requests url = "https://sph.pku.edu.cn/szdw/lxbywstjxx.htm" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.12022 SLBChan/25" } response = requests.get(url, headers=headers) response.encoding = response.apparent_encoding content = response.text html = etree.HTML(content) list = html.xpath("/html/body/div[3]/div/div/div[3]/div[2]/ul/li/div[1]/a") for a in list: link = a.xpath(".//@href")[0] detail_url = urljoin(url, link) # print(link) new_response = requests.get(detail_url, headers=headers) new_response.encoding = new_response.apparent_encoding new_content = new_response.text new_html = etree.HTML(new_content) div = new_html.xpath("/html/body/div/div[4]/div/div/div[3]/div[2]/form[1]/div[1]/div[2]") for div in div: name = div.xpath(".//h2/span/text()") email = div.xpath(".//ul/li[2]/span/text()") name = str(name)[2:-2] email = str(email)[2:-2] print(name) print(email)
时间: 2023-06-07 07:09:39 浏览: 56
这段代码使用Python,导入urllib.parse和lxml.etree模块以及requests模块来爬取指定网站的信息。使用requests模块发起一个GET请求获取网页内容,并使用etree模块来解析HTML文档。其中,使用xpath方法从HTML文档中获取所需信息,再使用urljoin方法将相对链接转换为绝对链接。
相关问题
from urllib.parse import quote, unquote
这是两行Python代码,它们分别导入了urllib.parse模块中的quote和unquote函数。在Web开发中,URL编码是一种常见的处理方式。由于URL中只能包含ASCII字符集中的部分字符,为了在URL中传递其他字符,我们需要对其进行编码。quote函数可以将字符串中的非ASCII字符和特殊字符进行编码,生成符合URL规范的字符串;而unquote函数则可以将编码后的字符串解码成原始字符串。在Python中,使用这两个函数可以方便地进行URL编码和解码。
import re import urllib.request import urllib.error import urllib.parse import json
这是一段 Python 代码,其中导入了几个模块,分别是 re、urllib.request、urllib.error、urllib.parse 和 json。re 模块是正则表达式模块,用于处理字符串匹配和替换;urllib.request、urllib.error 和 urllib.parse 模块是 Python 内置的 HTTP 客户端库,用于发送 HTTP 请求和处理响应;json 模块是 Python 内置的 JSON 编码和解码模块,用于处理 JSON 格式的数据。