python - 如何在python中抓取td标签内的链接

标签 python web-scraping beautifulsoup

这是我从网站上找到的 html 代码。 我想要vk link它位于 td 标记内。

我在 python 中尝试了很多方法来抓取该链接,但它总是显示某种类型的错误,有时它显示不同的链接。

<thead>
<tr class="footable-header">
<th scope="col" 
class="ninja_column_0 
ninja_clmn_nm_date ">Date</th><th scope="col"class="ninja_column_1ninja_clmn_nm_download">download</th></tr></thead><tbody><tr data-row_id="0" 
class="ninja_table_row_0 nt_row_id_0"><td>01-05-2022</td><td>https://vk.com/doc722551386_632783806? hash=gjIfCA0ILqZ1LQlzftCyxZ4zOATANYnUqZXiZ1vsAJH&dl=5wFKrFiIzvVfYJ6M4m1z9ALqKzGdXJdsGAXv1NaBtSg</td> </tr>

这是我尝试过的python代码:

import requests
from bs4 import BeautifulSoup

url="https://www.careerswave.in/dainik-jagran-newspaper-download/"
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text,'html.parser')
f = open("vkdain.txt", "w")
for link in soup.find_all("a"):
data = link.get('href')
print(data)

最佳答案

如果您只想获取 td 中的链接,这对我有用:

import requests
from bs4 import BeautifulSoup

url = "https://www.careerswave.in/dainik-jagran-newspaper-download/"
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'html.parser')
f = open("vkdain.txt", "w")
for link in soup.find_all("td"): # find all the td's
    if link.text.startswith('https://vk'): # check if the pattern is the one you want
        print(link.text)

这将为您带来以下结果:

https://vk.com/doc722551386_632783806?hash=gjIfCA0ILqZ1LQlzftCyxZ4zOATANYnUqZXiZ1vsAJH&dl=5wFKrFiIzvVfYJ6M4m1z9ALqKzGdXJdsGAXv1NaBtSg
https://vk.com/doc722551386_632705478?hash=mXInLmfkZNSLz5UVqRoRW60bRlzynUFUpRZoiBeW4ko&dl=zFzHm0Edhycg4ulJp33jdeFbypSaynNcjpZ41cUnID0
...
https://vk.com/doc623586997_607921843?hash=c6f706ee5f09f4d4e5&dl=f780520e509b9f671b
https://vk.com/doc623586997_607809766?hash=ef486a0fb1e873640e&dl=eeb60781cef9e58541

以下是一些相关问题:

关于python - 如何在python中抓取td标签内的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72074060/

相关文章:

python - 在 Linux 启动时运行 python3 应用程序

python - Beautifulsoup 正在从表中提取四舍五入的小数(可见的)而不是实际的单元格值

html - 使用 rvest 跟随 "next"与相对路径的链接

python - Scrapy 是否可以从原始 HTML 数据中获取纯文本?

python - 如何用空格替换标签 Beautiful Soup

python - 使用列表/字典中的值在数据框中创建新行

python - Union 赋值中的不兼容类型

python - 如何使用 Paramiko 从远程机器上执行的命令中获取 stderr 返回值?

python - 如何在Instagram上刮喜欢

python - 使用 Python 抓取 Ajax