【问题标题】:BeautifulSoup scraping not finding all 'a' tagsBeautifulSoup 抓取未找到所有“a”标签
【发布时间】:2021-01-21 13:11:19
【问题描述】:

我有一些代码,它曾经可以工作,但由于网站上的更改不再有效。 我正在尝试从 Apple 页面中获取所有 a 标记,以编译已弃用方法的列表 - 就像此处列出的方法:https://developer.apple.com/documentation/quartzcore?language=objc

可以在此处找到这些可能包含已弃用方法的方法:https://developer.apple.com/documentation/technologies/

其中按部分列出了方法 - 这里是 Accelerate 的一个,

<a data-v-2c210164="" data-v-012d2acf="" href="/documentation/accelerate" class="card" aria-labelledby="card_title_26" aria-describedby="card_content_26"><div data-v-2c210164="" class="card__content"><p data-v-2c210164="" id="card_title_26" aria-label="Accelerate" class="card__title">Accelerate</p></a>

尽管是a 标记,但以下代码不会在href 标记中拾取/documentation/accelerate,而是拾取页面上的其他链接,例如页脚。

headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Max-Age': '3600',
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
        }

url = "https://developer.apple.com/documentation/technologies"
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, 'html.parser')


for a in soup.find_all('a', href=True):
    print str(a)

我做错了什么? 我也尝试过其他匹配,例如for a in soup.find_all('a', class_=card):,但这也没有得到任何结果。 我的猜测是它可以从 Javascript 或其他东西中提取?

【问题讨论】:

  • 你是对的,数据是从 javascript 中提取的。你应该尝试使用selenium

标签: python web-scraping beautifulsoup


【解决方案1】:

会发生什么?

如果你看一下你的汤,你会确定,响应中没有这样的<a>。所以你找不到它。

原因是,页面正在处理动态内容。

如何解决?

你可以使用 selenium 来抓取page_source,因为 selenium 可以很好地处理动态内容:

示例

from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep

driver = webdriver.Chrome(executable_path='C:\Program Files\ChromeDriver\chromedriver.exe')
url = "https://developer.apple.com/documentation/technologies"

driver.get(url)
sleep(2)

soup = BeautifulSoup(driver.page_source, 'lxml')


for a in soup.find_all('a', href=True):
    print(a)
    
driver.close()

【讨论】:

  • 想了很多,谢谢。对于其他发现此问题的人 - 如果您使用的是 macOS,则需要 chromedriver brew install chromedriver 并从上述答案中删除 executable_path=
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多