【问题标题】:Python: BeautifulSoup - Get an attribute value from the name of a classPython:BeautifulSoup - 从类名中获取属性值
【发布时间】:2017-12-22 14:58:54
【问题描述】:

我正在从网页中抓取项目(其中有多个):

<a class="iusc" style="height:160px;width:233px" m="{&quot;cid&quot;:&quot;T0QMbGSZ&quot;,&quot;purl&quot;:&quot;http://www.tti.library.tcu.edu.tw/DERMATOLOGY/mm/mmsa04.htm&quot;,&quot;murl&quot;:&quot;http://www.tti.lcu.edu.tw/mm/img0035.jpg&quot;,&quot;turl&quot;:&quot;https://tse2.mm.bing.net/th?id=OIP.T0QMbGSZbOpkyXU4ms5SFwEsDI&amp;pid=15.1&quot;,&quot;md5&quot;:&quot;4f440c6c64996cea64c975389ace5217&quot;}" mad="{&quot;turl&quot;:&quot;https://tse3.mm.bing.net/th?id=OIP.T0QMbGSZbOpkyXU4ms5EsDI&amp;w=300&amp;h=200&amp;pid=1.1&quot;,&quot;maw&quot;:&quot;300&quot;,&quot;mah&quot;:&quot;200&quot;,&quot;mid&quot;:&quot;C303D7F4BB661CA67E2CED4DB11E9154A0DD330B&quot;}" href="/images/search?view=detailV2&amp;ccid=T0QMbGSZ&amp;id=C303D7F4BB661E2CED4DB11E9154A0DD330B&amp;thid=OIP.T0QMbGSZbOpkyXU4ms5SFwEsDI&amp;q=searchtearm;amp;simid=6080204499593&amp;selectedIndex=162" h="ID=images.5978_5,5125.1" data-focevt="1"><div class="img_cont hoff"><img class="mimg" style="color: rgb(169, 88, 34);" height="160" width="233" src="https://tse3.mm.bing.net/th?id=OIP.T0QMbGSZ4ms5SFwEsDI&amp;w=233&amp;h=160&amp;c=7&amp;qlt=90&amp;o=4&amp;dpr=2&amp;pid=1.7" alt="Image result fsdata-bm="169" /></div></a>

我想要做的是在m 属性中下载图像和与之关联的信息。

为此,我尝试了类似的方法来获取属性:

links = soup.find_all("a", class_="iusc")

然后,为了获得m 属性,我尝试了这样的方法:

for a in soup.find_all("m"):
    test = a.text.replace("&quot;" '"')
    metadata = json.loads(test)["murl"]
    print(str(metadata))

但是,这并没有按预期工作,并且没有打印任何内容(也没有错误)。

【问题讨论】:

  • 您确定要遍历 m 属性吗?在执行任何其他操作之前尝试打印 a 的值(在循环内)。
  • @Himal 没有打印出来。我做错了吗?

标签: python beautifulsoup python-3.5


【解决方案1】:

您没有遍历links 列表。试试这个。

links = soup.find_all("a", class_="iusc")

for link in links:
    print(link.get('m'))

【讨论】:

  • 工作就像一个魅力,我肯定是想多了。
猜你喜欢
  • 2021-12-04
  • 2010-10-26
  • 2012-01-08
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多