如何使用 Python、请求和 Beautiful soup 查找与关键字关联的 Link
How to Find Link Associated with Keyword using Python, Requests, and Beautiful soup
我很新 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>
我想做的是通过然后打印存储在 .
中的与之关联的 link 来获取关键字
要查找所有需要的内容,请为其添加要查找的标签。如果您只想要包含单词 "Yeezy" 的该类型的标签,那么在您的 for 循环中检查标签的文本是否是您要查找的字符串。如果它是您正在寻找的字符串,那么您就有了想要的元素并且可以打印 url.
对于大多数 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()
因为此时您正在尝试获取图像,所以您可能还想查看 。您需要一个可以读取和存储图像的库,而不是尝试将其作为内置 python 对象进行访问。
我很新 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>
我想做的是通过然后打印存储在 .
中的与之关联的 link 来获取关键字要查找所有需要的内容,请为其添加要查找的标签。如果您只想要包含单词 "Yeezy" 的该类型的标签,那么在您的 for 循环中检查标签的文本是否是您要查找的字符串。如果它是您正在寻找的字符串,那么您就有了想要的元素并且可以打印 url.
对于大多数 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()
因为此时您正在尝试获取图像,所以您可能还想查看