BeautifulSoup 4: 从不同的 ptag(s) 中提取多个标题和链接

BeautifulSoup 4: Extracting multiple titles and links from different ptag(s)

HTML代码:

<div>
    <p class="title">
       <a href="/news/123456">title_1</a> 
    </p>
</div>

<div>
    <p class="title">
       <a href="/news/789000">title_2</a> 
    </p>
</div>

我的代码:

def web(WebUrl):
    site = urlparse(WebUrl)
    code = requests.get(WebUrl)
    plain = code.text
    s = BeautifulSoup(plain, "html.parser")
    p_containers = s.find('p', {'class':'title'})

    for title in s.find_all('p', {'class':'title'}):
        line = title.get_text()
        print(line)
        for link in p_containers.find_all('a'):
            line2 = link.get('href')
            print(site.netloc + str(line2))

大家好,我需要一些帮助,我的任务是从网页中提取标题和 links,我能够提取标题但不能提取 links。当我尝试抓取 links 时,我只成功抓取了第一个 link,随后的 links 被忽略并替换为第一个抓取的 link.

您的代码中包含了大部分内容,但只是少了一点。我认为获取标题和链接的最简单方法是使用下面的方法。

site = """<div>
    <p class="title">
       <a href="/news/123456">title_1</a> 
    </p>
</div>

<div>
    <p class="title">
       <a href="/news/789000">title_2</a> 
    </p>
</div>"""

s = BeautifulSoup(site, "html.parser")

for title in s.find_all('p', {'class':'title'}):
    links = [x['href'] for x in title.find_all('a', href=True)]
    line = title.get_text()
    print(line)
    print(links)

您可以看到链接 object 是一个列表,以防每个标题有多个链接的情况。

尝试这种方式将有助于从中获得 find_all 值。

from bs4 import BeautifulSoup

text = """<div>
    <p class="title">
       <a href="/news/123456">title_1</a> 
    </p>
</div>

<div>
    <p class="title">
       <a href="/news/789000">title_2</a> 
    </p>
</div>
"""

soup = BeautifulSoup(text, 'html.parser')
for i in soup.find_all('p', attrs={'class': 'title'}):
    link = None
    if i.find('a'):
        link = i.find('a').get('href')
    print('Title:', i.get_text(strip=True), 'Link:', link)
# Output as:
# Title: title_1 Link: /news/123456
# Title: title_2 Link: /news/789000