【发布时间】:2019-06-01 16:23:05
【问题描述】:
我想使用类列表章节从 UL 获取所有链接,但我只得到我想要的链接的一半,因为链接被分隔在两个 <ul> 中,它们位于一个 div 中,就像 <div><ul>links1</ul><ul>links2</ul></div> 一样。我是 python 新手,我真的被困住了。
如果可能的话,我想在每个链接之前添加“http://www.example.com”并将它们一一保存在列表中,以便我可以使用 list[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()
【问题讨论】:
-
“一分为二”是什么意思?你能举个例子吗?
-
我的错,在 div.row 里面有两个 ul.list-chapter
-
您能否复制并粘贴您要解析的
div的确切HTML 代码?
标签: python html python-3.x web-scraping beautifulsoup