【问题标题】:how to get the content of a title using BeautifulSoup4 and requests如何使用 BeautifulSoup4 和 requests 获取标题的内容
【发布时间】:2021-07-27 13:40:54
【问题描述】:

所以我从这个链接中取了药物的标题:Medicines List

现在我想获取每种药物的内容,同时每种药物都有它自己的链接 例子 : Medicines Example

如何使用 BeautifulSoup4 和请求库获取该药物的内容?

import requests
from bs4 import BeautifulSoup
from pprint import pp

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0'
}


def main(url):
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'lxml')
    title = [x.text for x in soup.select(
        'a[class$=section__item-link]')]
    count = 0
    for x in range (0, len(title)):
        count += 1
        print("{0}. {1}\n".format(count, title[x]))


main('https://www.klikdokter.com/obat')

【问题讨论】:

  • 从您使用soup.select 找到的链接中获取hrefs,并分别请求他们的页面,并为每个页面发出新的获取请求
  • 如果有 500 种不同的药物,我需要为每种药物申请?

标签: python beautifulsoup python-requests


【解决方案1】:

根据我所看到的来自https://www.klikdokter.com/obat 的响应,您应该能够执行以下操作:-

import requests
from bs4 import BeautifulSoup
AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_5_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'
BASEURL = 'https://www.klikdokter.com/obat'
headers = {'User-Agent': AGENT}
response = requests.get(BASEURL, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
for tag in soup.find_all('a', class_='topics-index--section__item-link'):
    href = tag.get('href')
    if href is not None:
        print(href)
        response = requests.get(href, headers=headers)
        response.raise_for_status()
        """ Do your processing here """

【讨论】:

  • 好吧,这里只显示每种药物的链接,如果我想像药物描述一样获取药物的内容,我应该怎么做?
  • 您需要处理来自我的代码打印的每个 URL 的响应数据
  • 所以我需要为每个站点做请求?你能给我举个例子吗?因为我是新手
  • 是的,这正是我的代码所展示的。您已经知道如何解析来自主站点的 HTML 响应,因此只需对后续请求执行相同的操作即可。这一切都取决于您要提取的内容
猜你喜欢
  • 1970-01-01
  • 2021-04-22
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多