使用Selenium Python抓取网站文章时无法批量获取URL的问题求助
批量获取文章URL的解决方案
我明白你现在的困扰:已经成功拿到了标题和日期的列表,但批量抓取文章URL的时候卡壳了——之前尝试的代码没起作用,对吧?
咱们先拆解问题根源:你原来的代码里,news_links定位的是页面上的<h3>元素,但文章的跳转链接其实是嵌套在<h3>里面的<a>标签里的。你之前写的news_links.find_elements_by_tag_name('a')会报错,因为news_links是一个元素列表,不是单个元素,没法直接在它上面调用查找方法。
下面给你两种简单的解决办法,任选其一就行:
方法一:直接定位到<a>标签(最省心)
直接修改XPath,让它直接找到每个标题对应的<a>标签,这样就能一次性拿到标题文本和URL,还能保证顺序完全对应:
def sb_rum(): websites = ['https://www.thespiritsbusiness.com/tag/rum/'] for spirits in websites: browser.get(spirits) time.sleep(1) # 直接定位h3下的a标签,这是文章的跳转链接 news_items = browser.find_elements_by_xpath('//*[@id="archivewrapper"]/div/div[2]/h3/a') # 批量提取标题和URL n_titles = [ele.text for ele in news_items] n_urls = [ele.get_attribute('href') for ele in news_items] # 提取日期列表(和原来的代码逻辑一致) dates = browser.find_elements_by_xpath('//*[@id="archivewrapper"]/div/div[2]/small') n_dates = [ele.text for ele in dates] # 把标题、日期、URL对应起来打印,验证匹配性 for title, date, url in zip(n_titles, n_dates, n_urls): print(f"标题: {title}") print(f"日期: {date}") print(f"URL: {url}\n")
方法二:遍历每个<h3>元素找<a>标签
如果你不想修改原来的<h3>定位逻辑,也可以逐个遍历<h3>元素,在每个里面找到对应的<a>标签再提取URL:
def sb_rum(): websites = ['https://www.thespiritsbusiness.com/tag/rum/'] for spirits in websites: browser.get(spirits) time.sleep(1) # 先定位所有h3元素 news_h3s = browser.find_elements_by_xpath('//*[@id="archivewrapper"]/div/div[2]/h3') n_titles = [] n_urls = [] # 遍历每个h3,找到里面的a标签 for h3 in news_h3s: a_tag = h3.find_element_by_tag_name('a') n_titles.append(a_tag.text) n_urls.append(a_tag.get_attribute('href')) # 提取日期列表 dates = browser.find_elements_by_xpath('//*[@id="archivewrapper"]/div/div[2]/small') n_dates = [ele.text for ele in dates] # 验证输出内容 for title, date, url in zip(n_titles, n_dates, n_urls): print(f"标题: {title}") print(f"日期: {date}") print(f"URL: {url}\n")
小提醒
如果运行时还是有问题,记得打开浏览器的开发者工具(F12)检查一下页面结构,确认<a>标签确实嵌套在<h3>里面,而且XPath的路径没有写错——有时候网站的页面结构可能会微调,这时候就要更新一下定位路径啦。
内容的提问来源于stack exchange,提问作者technophile_3
相关产品推荐
相关产品推荐

