python - 如何使用 BeautifulSoup4 只获取 "href"?

标签 python beautifulsoup

我试图仅从find_all()的结果中获取链接

这是我的代码:

    mydivs = soup.find_all("td", {"class": "candidates"})
    for link in mydivs:
        print(link)

但它返回:

<td class="candidates"><div><a data-tn-element="view-unread-candidates" data-tn-link="true" href="/c#candidates?id=a722443b402&amp;ctx=jobs-tab-view-candidates">56 candidates</a><br/><a data-tn-element="view-unread-candidates" data-tn-link="true" href="/c#candidates?id=a7b2a139b402&amp;candidateFilter=4af15d8991a8"><span class="jobs-u-font--bold">(45 awaiting review)</span></a></div></td>

我想要得到什么:

/c#candidates?id=a722443b402&amp;ctx=jobs-tab-view-candidates

最佳答案

将 bs4 元素转换为字符串后,您可以使用正则表达式解析 href 和最后一个引号之间的所有内容。

import re

#Rest of imports/code up until your script. 

mydivs = soup.find_all("td", {"class": "candidates"})
or link in mydivs:
   link_text = str(link)
   href_link = re.search('href = "(.+?)"', link_text)
   print(href_link.group(1))

下面显示的小示例:

import re

link_text = '<td class = "candidates" > <div > <a data-tn-element = "view-unread-candidates" data-tn-link = "true" href = "/c#candidates?id=a722443b402&amp;ctx=jobs-tab-view-candidates" > 56 candidates < /a > <br/> < a data-tn-element = "view-unread-candidates" data-tn-link = "true" href = "/c#candidates?id=a7b2a139b402&amp;candidateFilter=4af15d8991a8" > <span class = "jobs-u-font--bold" > (45 awaiting review) < /span > </a > </div > </td >'
href_link = re.search('href = "(.+?)"', link_text)
print(href_link.group(1))

输出:

/c#candidates?id=a722443b402&amp;ctx=jobs-tab-view-candidates

您可能需要使用 re.search 内部的 href = " 来处理间距,因为我看不到标签的样子。但您所需要做的就是复制确切的文本从 href 到您希望其起作用的链接的第一个字符。

关于python - 如何使用 BeautifulSoup4 只获取 "href"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56082778/

相关文章:

python - 使用 BeautifulSoup 和 Requests 提取 html 单元格数据

python - 使用 argparse 从标准输入或输入文件中读取

python - numpy:对操作结果执行 "any"或 "all"的有效方法

python - 屏蔽矩阵行中的最小值

python - 如何通过 Python 抓取动态网页

python - 在 BeautifulSoup 中打印最后一个 <td>

python - 如何从 HowLongToBeat.com 抓取信息?它不在 URL 中使用变量

python : javabridge virtual machine only works once

python - 如何使用 Python 抓取网站中嵌入的表格

python - 在 AJAX 请求完成后抓取页面