首页 > 解决方案 > 从多个获取链接

问题描述

我想使用类列表章节从 U​​L 获取所有链接,但我只得到我想要的链接的一半,因为链接被分成两个<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()

标签: pythonhtmlpython-3.xweb-scrapingbeautifulsoup

解决方案


您正在使用findwhich 将返回第一个匹配项,而不是find_allwhich 将返回匹配项列表。

假设您的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 /

推荐阅读