【问题标题】:How to Find Link Associated with Keyword using Python, Requests, and Beautiful soup如何使用 Python、Requests 和 Beautiful soup 找到与关键字相关的链接
【发布时间】:2017-07-01 17:58:55
【问题描述】:

我是非常新的 python 请求和漂亮的汤,所以我的代码可能真的很糟糕。

我现在拥有的:

f = open('sites.txt','r')
sitelist = []
for line in f:
    sitelist.append(line.strip())
getsites = ['']
print(sitelist)
for i in range(len(sitelist)):
    getsites.append(sitelist[i])

for i in range(len(sitelist)):
    temp = requests.get(sitelist[i])
    data = temp.text
    soup = BeautifulSoup(data, "html.parser")
    for url in soup.find_all("Yeezy"):
        print(element.find_previous_sibling('loc'))
        print(url.text)

我正在解析的 XML 文件示例:

<url>
<loc>
https://www.a-ma-maniere.com/products/beanie-502805f16-black-white
</loc>
<lastmod>2016-12-24T22:25:05Z</lastmod>
<changefreq>daily</changefreq>
<image:image>
<image:loc>
https://cdn.shopify.com/s/files/1/0626/9065/products/502805F16-1.jpg?v=1472499019
</image:loc>
<image:title>Alexander Wang: Beanie (Black/White)</image:title>
</image:image>
</url>

我想要做的是通过然后打印存储在中的与它关联的链接来获取关键字。

【问题讨论】:

  • 您正在寻找的关键字样本是什么?您认为哪个 XML 字段最符合您的关键字(即您在 XML 中的哪个位置查找关键字)?
  • 关键字出现在 标签中,因此例如在这个 xml 中,我将搜索“Alexander Wang”并尝试在对应的 <loc> 标签中找到产品位置/跨度> </loc>

标签: python web-scraping beautifulsoup python-requests shopify


【解决方案1】:

为了找到所有你需要给它一个标签来寻找。如果你只想要包含单词“Yeezy”的那种类型的标签,那么在你的 for 循环中检查标签的文本是否是你正在寻找的字符串。如果它是您要查找的字符串,那么您有需要的元素并且可以打印 url。

对于大多数网址来说,这只是

for url in soup.find_all('a')
    if "Yeezy" in url.get_text():
        print(url['href'])

更喜欢你的

for url in soup.find_all('url')
    if url.find('image:title') and url.loc:
        if "Yeezy" in url.find('image:title').get_text()
            print(url.find('image:loc').get_text())

更多信息请访问get_text()

因为此时您正在尝试获取图像,所以您可能还想查看this answer。您需要一个可以读取和存储图像的库,而不是尝试将其作为内置 python 对象进行访问。

【讨论】:

  • AttributeError: 'NoneType' 对象没有属性 'get_text'
  • 如果找不到任何东西,它将抛出该错误。有时,您会遇到没有您要查找的字段的标签。我编辑了答案,希望能解决这个问题。
  • 嘿,我更新了我的脚本,并试图让它在它抓取产品脚本的链接后抓取特定产品 xml 文件并抓取它的变体以将产品添加到您的购物车(Shopify网站)。但是我在第二个循环中遇到了错误,
  • 具体在这一行:soup2 = BeautifulSoup(prod_data, "html.parser")prod_data 是(prod_link 指的是在上一个循环中找到的链接):prod_data = requests.get(prod_link)
  • 我在答案末尾添加了一个附加参考,以便您可以查看名为 PIL 的内容。它应该有助于解决您现在遇到的错误。
猜你喜欢
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2019-07-22
相关资源
最近更新 更多