因此,我尝试通过提供大小ID来提取以下特定的href表单示例。例如,我希望值EU = '39'的那个我希望能够精确打印href是在分配EU 39的行中写的
<a href="/p/nike-air-force-1-07-prm-x-carhartt-wip-av4113-200-83890-83891" EU='38,5' US='6'>38,5</a>
<li title="">
<a href="/p/nike-air-force-1-07-prm-x-carhartt-wip-av4113-200-83890-83892" EU='39' US='6,5'>39</a>
<li title="">
<a href="/p/nike-air-force-1-07-prm-x-carhartt-wip-av4113-200-83890-83893" EU='40' US='7'>40</a>
<li title="">
<a href="/p/nike-air-force-1-07-prm-x-carhartt-wip-av4113-200-83890-83894" EU='40,5' US='7,5'>40,5</a>
<li title="">
<a href="/p/nike-air-force-1-07-prm-x-carhartt-wip-av4113-200-83890-83895" EU='41' US='8'>41</a>
<li title="">
到目前为止,我的代码如下。我找到了如何获取单个href的方法,但是我只想要那些具有所需大小ID以及特定关键字的对象。我尝试了一下,并且奏效了,但只是找到了所有带有该关键字的内容...。我只想获取具有特定值的内容...
import requests
from bs4 import BeautifulSoup as bs
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
s = requests.session()
scraper=cfscrape.create_scraper(sess=s)
link=input("link where I need to find the product: ")
keyword=["examplekeyword"]
def bs_id():
try:
r = scraper.get(link, timeout=2, verify=False, headers=header)
except:
print("error while connecting...")
try:
r = scraper.get(link, timeout=2, verify=False, headers=header)
except:
print("error while connecting")
return
page = bs(r.text, "html.parser")
raw_links = page.findAll("a")
hrefs = []
for raw_link in raw_links:
try:
hrefs.append(raw_link["href"])
except:
pass
for href in hrefs:
found = False
for keyword in keywords:
if(keyword.upper() in href.upper()):
found = True
if("http" in href):
product_page = href
else:
product_page = site + href
希望你们中的任何人都可以帮助我,我真的很陌生,所以每一个有帮助的评论都会很友好。非常感谢。
答案 0 :(得分:2)
您可以尝试这样的操作,而不是遍历hrefs,只需遍历整个“ a”标签,然后获取所需的href。这样一来,您只需要一个循环。
for link in page.find_all('a'):
if "EU='39'" in link:
print(link['href'])