python - 从多个获取链接同班
问题描述
我想使用类列表章节从 UL 获取所有链接,但我只得到我想要的链接的一半,因为链接被分成两个<ul>
在 div 中,就像这样<div><ul>links1</ul><ul>links2</ul></div>
。我是 python 新手,我真的被困住了。
另外,如果可能的话,我想在每个链接之前添加“ http://www.example.com ”并将它们一一保存在列表中,以便我可以使用列表 [1] 访问它们。
谢谢,这里是代码
# import libraries
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
"""Getting Started Example for Python 2.7+/3.3+"""
chapter = 1
chapterlist = 1
links = []
name = ""
reallink = ""
while chapter < 31:
quote_page = Request('http://website.com/page.html?page=' + str(chapter) + '&per-page=50', headers={'User-Agent': 'Mosezilla/5.0'})
page = urlopen(quote_page).read()
soup = BeautifulSoup(page, "html.parser")
name_box = soup.find("ul", attrs={"class": "list-chapter"})
links += name_box.find_all("a")
reallink += str([a['href'] for a in links])
chapter += 1
f = open("links.txt", "w+")
i = 1
f.write(reallink)
f.close()
解决方案
您正在使用find
which 将返回第一个匹配项,而不是find_all
which 将返回匹配项列表。
假设您的ul
课程是正确的,我将select
改为使用并收集a
这些的子标签:
替换这些行:
name_box = soup.find("ul", attrs={"class": "list-chapter"})
links += name_box.find_all("a")
reallink += str([a['href'] for a in links])
和
realinks = ['http://www.example.com' + item['href'] for item in soup.select('ul.list-chapter a')] #I'm assuming href already has leading /
推荐阅读
- python-3.x - Python re:获取引号或双引号
- azure - 本地化不适用于生产 - .NET core 3.1
- javascript - 如何设置状态以响应数组中某个索引处的内容
- javascript - 随机的 Javascript 和 typescript 文件内容更改为奇怪的字符,导致编译失败
- javascript - 如何在本机反应中使用 json 元素
- python - 调试在 VS Studio Code Django 中不起作用
- reactjs - Nextjs - 如果在客户端运行,则注入 ContextProvider
- c++ - 出现错误:致命错误:curl/curl.h:没有这样的文件或目录#include
- simulink - 使用 FMI Kit 从 Matlab Simulink 导出 fmu 时如何附加.xls/.csv/.txt 文件?
- reactjs - 如何在 REACT JS 中使用 axios 连接 URL 和字符串,并在单击按钮时从 API 获取数据