def parse(url): try: res = requests.get(url, headers=headers) html = etree.HTML(res.text) books = html.xpath('//ul[@class="bang_list clearfix bang_list_mode"]/li') for b in books: name = b.xpath('./div[@class="name"]/a/text()')[0] link = b.xpath('./div[@class="name"]/a/@href')[0] comment = b.xpath('./div[@class="star"]/a/text()')[0] author = b.xpath('./div[@class="publisher_info"][1]/a[1]/@title')[0] publisher = b.xpath('./div[@class="publisher_info"][2]/a/text()')[0] price_n = b.xpath('./div[@class="price"]/p[1]/span[@class="price_n"]/text()')[0] price_r = b.xpath('./div[@class="price"]/p[1]/span[@class="price_r"]/text()')[0]这段代码的意思
时间: 2023-06-24 10:08:50 浏览: 47
这段代码是一个Python函数,它接收一个URL参数,并使用requests库发送HTTP请求获取该URL对应的HTML网页。然后,使用etree库解析HTML文档,提取其中的书籍信息,并将其存储在一个字典中。
具体来说,该函数首先通过XPath表达式选取所有包含书籍信息的<li>元素。然后,对于每个<li>元素,使用XPath表达式提取书名、链接、评论、作者、出版社、价格等信息,并将其存储在一个字典中。最后,将所有字典存储在一个列表中,作为函数的返回值。
相关问题
import requests from urllib import parse #全局请求头 files = {} headers = {} body = {} timeouts = {} resHeader = {} class ShowapiRequest: def __init__(self, url, my_appId, my_appSecret): self.url = url self.my_appId = my_appId self.my_appSecret = my_appSecret body["1422355"] = my_appId body["24db7e66fd054eab98c921a5c807d97d"] = my_appSecret headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2427.7 Safari/537.36" def addFilePara(self, key, value_url): files[key] = open(r"%s" % (value_url), 'rb') return self def addHeadPara(self, key, value): headers[key] = value return self def addBodyPara(self, key, value): body[key] = value return self #设置连接时间和读取时间 def setTimeout(self, connecttimout, readtimeout): timeouts["connecttimout"] = connecttimout timeouts["readtimeout"] = readtimeout return self def get(self): get_url = self.url + "?" + parse.urlencode(body) if not timeouts: res = requests.get(get_url, headers=headers) else: timeout = (timeouts["connecttimout"], timeouts["readtimeout"]) res = requests.get(get_url, headers=headers, timeout=timeouts) return res def post(self): if not timeouts: res = requests.post(self.url, files=files, data=body, headers=headers) else: timeout = (timeouts["connecttimout"], timeouts["readtimeout"]) res = requests.post(self.url, files=files, data=body, headers=headers, timeout=timeout) return res
这段代码是一个 ShowapiRequest 类,用于调用 Showapi 平台的 API 接口。它通过构建请求参数、请求头和超时时间等信息来发送 HTTP GET 或 POST 请求,并返回响应结果。
在类的初始化方法中,会传入 Showapi 平台的 appid 和 secret,并在请求体中添加这些参数。此外,还会设置一个默认的 User-Agent 请求头。
类中的 `addFilePara`、`addHeadPara` 和 `addBodyPara` 方法用于添加文件参数、请求头参数和请求体参数,并返回实例自身。
`setTimeout` 方法用于设置连接和读取的超时时间。
`get` 和 `post` 方法分别用于发送 HTTP GET 和 POST 请求,并返回响应结果。其中涉及到请求参数、请求头、超时时间的使用。
下面的这段代码为什么会报错?应该怎么解决?import requests import re import os session = requests.Session() # (1) 爬取m3u8文件的链接 url = "https://www.9tata.cc/play/14999-1-0.html" headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36' } res = session.get(url, headers=headers, verify=False) m3u8_link = re.search('now="(.*?m3u8)"', res.text).group(1) print(m3u8_link) # https://ikcdn01.ikzybf.com/20221015/ecMSO74h/index.m3u8 print(os.path.dirname(m3u8_link)) # 顺便抓一个名字 # name = re.search(r'<td class="col2 hidden-xs">(?P<name>\w+)</td>', res.text).group("name") # print("name", name) # (2) 爬取m3u8文件 res = session.get(m3u8_link) print(res.text.split("\n")[2]) # m3u8_detail_link = os.path.join(os.path.dirname(m3u8_link), res.text.split("\n")[2]) print(m3u8_detail_link) # (3) 爬取m3u8具体文件 res = requests.get(m3u8_detail_link) print(res.text)
这段代码可能会报错因为:
1. 请求 `https://www.9tata.cc/play/14999-1-0.html` 返回的内容中可能没有符合正则表达式 `'now="(.*?m3u8)"'` 的内容,导致 `re.search` 函数返回 `None`,再调用 `.group(1)` 方法就会抛出 AttributeError。
2. 在注释 (2) 中,由于 `res.text.split("\n")[2]` 可能不存在,因此会抛出 IndexError。
3. 如果在注释 (2) 中成功获取到 `m3u8_detail_link`,由于该链接是相对链接,需要使用 `urllib.parse.urljoin` 函数将其与 `os.path.dirname(m3u8_link)` 拼接起来才能得到完整链接。
4. 在注释 (3) 中,使用了 `requests.get` 函数而不是之前创建的 `session.get` 方法,这意味着没有传递之前设置的 headers 和 cookies,可能会导致请求失败。
要解决这些问题,可以按照下面的方式修改代码:
```python
import requests
import re
import os
from urllib.parse import urljoin
session = requests.Session()
url = "https://www.9tata.cc/play/14999-1-0.html"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}
# (1) 爬取m3u8文件的链接
res = session.get(url, headers=headers, verify=False)
m3u8_match = re.search(r'now="(.*?m3u8)"', res.text)
if m3u8_match:
m3u8_link = m3u8_match.group(1)
print(m3u8_link)
# (2) 爬取m3u8文件
res = session.get(m3u8_link)
if res.ok:
m3u8_detail_link = urljoin(os.path.dirname(m3u8_link), res.text.split("\n")[2])
print(m3u8_detail_link)
# (3) 爬取m3u8具体文件
res = session.get(m3u8_detail_link)
if res.ok:
print(res.text)
else:
print("Failed to get m3u8_detail_link")
else:
print("Failed to get m3u8_link")
else:
print("Failed to find m3u8_link")
```