繁体   English   中英

如何通过使用python 3从“ a”中的href获得类名的链接

[英]How can I get the link from href in “a” with class name by using python 3

我试图从google map中获取链接,其元素是:

<div class="something1">
  <span class="something2"></span>
  <a data-track-id="Google Map" href="https://www.google.com/maps/dir//11111/@22222" target="_blank" class="something3">Google Map</a>
</div>

我只想得到https://www.google.com/maps/dir//11111/@22222

我的代码是

 gpslocation = []
 for gps in (secondpage_parser.find("a", {"data-track-id":"Google Map"})):
     gpslocation.append(gps.attrs["href"])

我正在使用2个网址页面(主页和第二页)来抓取位于第二页中的博客网站。 其他信息(例如Story-Title或Author Name get_text()可以作为文本显示,因此我可以使用get_text()

但是在这种情况下,我无法在href之后获得链接。 请帮忙。

PS。 在我只想要链接(11111和22222)中的纬度和经度的情况下,有没有办法使用str.rplit

非常感谢

您可以使用以下内容:

secondpage_parser.find("a", {"data-track-id":"Google Map"})['href']
  1. 使用soup.find(...)['href']查找具有href的所有链接,或使用soup.find_all('a' ... , href=True)查找所有链接

  2. 是的,您可以使用split来获得经纬度

    • 首先拆分//然后获取最新的[-1]
    • 然后在/@上分割以同时获得经度和纬度

from bs4 import BeautifulSoup

data = """
<div class="something1">
  <span class="something2"></span>
  <a data-track-id="Google Map" href="https://www.google.com/maps/dir//11111/@22222" target="_blank" class="something3">Google Map</a>
</div>
"""

soup = BeautifulSoup(data, "html.parser")
for gps in soup.find_all('a', href=True):
    href = gps['href']
    print(href)
    lati, longi = href.split("//")[-1].split('/@')
    print(lati)
    print(longi)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM