gpt4 book ai didi

python - 使用 Python 从网站源代码中提取 href 链接

转载 作者:行者123 更新时间:2023-11-27 23:35:44 31 4
gpt4 key购买 nike

我之前问过这个问题没有用。我想弄清楚如何实现 bs4 以获取用于从网站源代码下载的链接。我无法弄清楚的问题是链接位于动态内容库中。 我删除了之前的 html 片段,请看下面

只有手动从网站上抓取源代码后,我们才能用这个脚本抓取链接:

import re
enter code here

line = line.rstrip()
x = re.findall('href=[\'"]?([^\'" >]+)tif', line)
if len(x) > 0 :
result.write('tif">link</a><br>\n<a href="'.join(x))

`result.write('tif">link</a><br>\n\n</html>\n</body>\n')

result.write("There are " + len(x) + " links")


print "Download HTML page created."

但只有在进入网站后 ctrl + a -> 查看源代码 -> 全选并复制 -> 粘贴到 SourceCode.txt 上。我想从这一切中消除体力劳动。

如果有任何信息/提示/建议,我将不胜感激!

编辑

我想添加一些关于我们正在使用的网站的更多信息,图书馆内容只有在手动展开后才会显示。否则,内容(即下载链接/href *.tif)不可见。这是我们所看到的示例:

未打开库元素的站点源代码。

<html><body>

打开库元素后的源代码。

<html><body>
<h3>Library</h3>
<div id="libraryModalBody">

<div><table><tbody>

<tr>
<td>Tile12</td>
<td><a href="http://www.website.com/path/Tile12.zip">Button</a></td>
</tr>

</tbody></table></div>

</div>

展开所有下载选项后的源代码。

<html><body>
<h3>Library</h3>
<div id="libraryModalBody">
<div><table><tbody>
<tr>
<td>Tile12</td>
<td><a href="http://www.website.com/path/Tile12.zip">Button</a></td>
</tr>
<tr>
<td>Tile12_Set1.tif</td>
<td><a href="http://www.website.com/path/Tile12_Set1.tif">Button</a></td>
</tr>
<tr>
<td>Tile12_Set2.tif</td>
<td><a href="http://www.website.com/path/Tile12_Set2.tif">Button</a></td>
</tr>
</tbody></table></div>
</div>

我们的最终目标是只需输入网站 url 即可获取下载链接。问题似乎在于内容的显示方式(即动态内容仅在手动扩展库后可见。

最佳答案

不要尝试使用正则表达式解析 HTML。 It's not possibleit won't work .请改用 BeautifulSoup4:

from urllib2 import urlopen
from bs4 import BeautifulSoup

url = "http://www.your-server.com/page.html"
document = urlopen(url)
soup = BeautifulSoup(document)

# look for all URLs:
found_urls = [link["href"] for link in soup.find_all("a", href=True)]

# look only for URLs to *.tif files:
found_tif_urls = [link["href"] for link in soup.find_all("a", href=True) if link["href"].endswith(".tif")]

关于python - 使用 Python 从网站源代码中提取 href 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33897171/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com