大佬教程收集整理的这篇文章主要介绍了无法使用 Beautifulsoup 正确抓取 <strong> 标签,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我尝试使用以下代码从 adidas website 中抓取产品的日期:
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/'
'84.0.4147.105 Safari/537.36'}
url = "https://www.adIDas.com.sg/release-dates"
productsource = requests.get(url,headers=headers,timeout=15)
producTinfo = BeautifulSoup(productsource.text,"lxml")
def jdMonitor():
# webscraper
all_items = producTinfo.find_all(name="div",class_="gl-product-card")
# print(all_items)
for item in all_items:
# print(item)
pname = item.find(name="div",class_="plc-product-name___2cofu").text
pprice = item.find(name="div",class_="gl-price-item").text
imagelink = item.find(name="img")['src']
plink = f"https://www.adIDas.com.sg/{item.a['href']}"
try:
PDAte = item.find(name="div",class_="plc-product-date___1zgO_").strong.text
except AttributeError as e:
print(E)
PDAte = "Data Not Available"
print(f"""
Product name: {pnamE}
Product Price: {ppricE}
Image link: {imagelink}
Product link: {plink}
Product Date: {PDAtE}
""")
jdMonitor()
但我在 PDAte
中得到一个空字符串。但是如果我使用 print(producTinfo.find_all(name="strong"))
提取页面上的所有强标签,我能够正确提取所有标签,而不是我需要的标签。我得到的输出为:
... <strong>All Recycled Materials</strong>,<strong> </strong> ...
第二对强标记之间的空白区域应包含类似日期
<strong>Wednesday 30 Jun 21:30</strong>
有人可以解释为什么会发生这种情况吗?以及提取它的方法。
似乎日期是动态更新的,源代码中没有这样的日期(打开源代码并查找“Wednesday 30 JUN 19:00”,什么都不会显示)。最明显的是使用 SELEnium
使其工作,但这可能是一个缓慢的解决方案。 requests-html
对我不起作用,就像 bs4
一样。呈现页面也无济于事(或者我做错了什么)。
from SELEnium import webdriver
from SELEnium.webdriver.chrome.options import Options
options = Options()
# running in headless mode for some reason gives no result or throws an error.
# options.headless = True
driver = webdriver.Chrome(options=options)
driver.get('https://www.adidas.com.sg/release-dates')
for date in driver.find_elements_by_css_SELEctor('.plc-product-date___1zgO_.gl-label.gl-label--m.gl-label--condensed'):
print(date.text)
driver.quit()
# output:
'''
Wednesday 30 JUN 19:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
THURSDAY 01 JUL 05:00
'''
您也可以像这样使用 regex
来获取这个日期(如果它们会出现):
import re
test = '''
Wednesday 30 Jun 19:00
THURSDAY 01 JUL 05:00
THURSDAY 01 FEb 25:00
'''
matches = re.findall(r"[a-zA-Z]+\s\d+\s\w+\s\d+:\d+",str(test))
finall_R_1_11845@atches = '\n'.join(matches)
print(finall_R_1_11845@atches)
# output before joining: "['Wednesday 30 Jun 19:00','THURSDAY 01 JUL 05:00','THURSDAY 01 FEb 25:00']"
# output after joining:
'''
Wednesday 30 Jun 19:00
THURSDAY 01 JUL 05:00
THURSDAY 01 FEb 25:00
'''
以上是大佬教程为你收集整理的无法使用 Beautifulsoup 正确抓取 <strong> 标签全部内容,希望文章能够帮你解决无法使用 Beautifulsoup 正确抓取 <strong> 标签所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。