【问题标题】:Fetching links from multiple <ul> with same class从具有相同类的多个 <ul> 中获取链接
【发布时间】:2019-06-01 16:23:05
【问题描述】:

我想使用类列表章节从 U​​L 获取所有链接,但我只得到我想要的链接的一半,因为链接被分隔在两个 &lt;ul&gt; 中,它们位于一个 div 中,就像 &lt;div&gt;&lt;ul&gt;links1&lt;/ul&gt;&lt;ul&gt;links2&lt;/ul&gt;&lt;/div&gt; 一样。我是 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


【解决方案1】:

您使用的是find,它将返回第一个匹配项,而find_all 将返回匹配项列表。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多