python - 抓取并提取多个元素

标签 python python-3.x beautifulsoup web-crawler

我尝试从某个网站抓取信息,以获取 YouTube channel 中的多个名称、其所属国家/地区及其网址的数据。现在可以抓取 channel 名称和url信息。我的目标是提取特定 YouTube channel 的国家/地区,但有时此信息可能会丢失。现在我可以提取每个 channel 的 URL 和 channel 名称,但我不知道如何提取标题,例如:title="Romania"。我尝试使用正则表达式,但问题是 标题 有时在 header 中包含两次。以下代码演示了我当前的过程:

from bs4 import BeautifulSoup
import re
import requests

for i in range(1, 300):
    url = "https://www.channelcrawler.com/eng/results/136630/page:%s" % i
    req = requests.get(url)
    data = req.text
    soup = BeautifulSoup(data, "html.parser")

    for link in soup.find_all('h4'):
        #for t in link.find_all('title'):
        print(link)
        row = str(link)
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', row)
        print(urls)
        #print(link.text.strip())
        print(link.get_text())

Output:
<h4>
<a href="http://www.youtube.com/channel/UCWmSq95JfUZTv1-Jxmkk-Rw" target="_blank" title="Ford South Africa">Ford South Africa</a> </h4>
['http://www.youtube.com/channel/UCWmSq95JfUZTv1-Jxmkk-Rw']
...
<h4>
<a href="http://www.youtube.com/channel/UCyfWjPOye4zFvEC_MkbJZ4w" target="_blank" title="Nutz Rider">Nutz Rider</a> <img alt="" src="/img/flags/gif/ro.gif" title="Romania"/> </h4>
['http://www.youtube.com/channel/UCyfWjPOye4zFvEC_MkbJZ4w']

最佳答案

试试这个..

from bs4 import BeautifulSoup
import re
import requests

    for i in range(1, 300):
        url = "https://www.channelcrawler.com/eng/results/136630/page:%s" % i
        req = requests.get(url)
        data = req.text
        soup = BeautifulSoup(data, "html.parser")

        for link in soup.find_all('h4'):
            a = link.find('a')
            print(a['href'])
            print(a['title'])
            print(a.text)
            a = link.find('img')
            print(a['title'])
        break    

您可以将国家/地区放在方括号中,然后将内容放入 try catch 中。希望这会有所帮助

注意:插入测试中断

关于python - 抓取并提取多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746996/

相关文章:

python - 重用最后一行 Jupyter 的结果

python检查字典是否在列表中

python - 从多行字符串中剥离 "\n",内联时除外

python - 如何使用漂亮的汤 python 从脚本标签中提取 json?

python - 无法在 Instagram 公共(public)帐户上抓取超过 12 个帖子

Python 从 tripadvisor 抓取 'things to do'

python - 在多个模型上使用单个多对多关系表而不是多对多和外键字段?

python - 如何在 Haystack 中指定预测列?

python - 属性错误 : 'NoneType' object has no attribute 'get' - Python - OpenErp

python - 想要将列表的元素更改为Python中的字典键