Webscrape CNN,注入,美丽的汤,python,请求,HTML



好吧,我以为我疯了,因为我在这方面一再失败,但我想,也许html发生了一些我不理解的事情。

我一直在努力从cnn.com.上搜集"文章">

但无论我用哪种方式尝试汤.find_all('articles'(或汤.find('body'(.div('div'(……带有类标签、id等,都失败了。

我发现了这个参考:在componentDidMount之后,从React web应用程序中进行Webscratch。

我怀疑html中的注入是我遇到问题的原因。

我从网络安全阅读中知道0关于"html注入攻击"以外的注入。

我想要这些文章,但我认为我需要使用类似于上面其他堆栈溢出问题链接的策略。我不知道怎么做。链接到帮助文件或特别是cnn抓取将不胜感激。

或者,如果有人知道我如何获得html body元素的"完整数据",这样我就可以在这个定义的早期代码中进行一些重新排列,然后重新分配body。

"或者告诉我我是个白痴,走错了路">

def build_art_d(site):

url = site
main_l = len(url)

html = requests.get(url).text
soup = BeautifulSoup(html, 'lxml')

print(soup.prettify())

art_dict = {}

body = soup.find('body')
print(body.prettify())
div1 = body.find('div', {'class':'pg-no-rail pg-wrapper'})
section = div1.find('section',{'id' : 'homepage1-zone-1'})
div2 = section.find('div', {'class':'l-container'})
div3 = div2.find('div', {'class':'zn__containers'})
articles = div3.find_all('article')

for art in articles:
art_dict[art.text] = art.href


#test print
for article in art_dict:
print('Article :: {}'.format(article), 'Link :: {}'.format(art_dict[article]))

您可以使用selinium来启用由站点javascript填充的数据。然后使用现有的bs4代码来抓取文章。

from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.cnn.com/')
soup = BeautifulSoup(driver.page_source, 'html.parser')

最新更新