回答編集履歴

1

Update

2022/07/31 08:33

投稿

melian
melian

スコア19825

test CHANGED
@@ -1,39 +1,25 @@
1
+ > 以下のようなサイトのサイトマップから
2
+
3
+ 実際には a 要素ではなく ul 要素になっているので、`a:has(...)` を `ul:has(...)` に変更します。
4
+
1
5
  ```python
2
6
  from bs4 import BeautifulSoup
7
+ import requests
3
8
 
9
+ url = "https://type.jp/tensyoku-knowhow/contents-sitemap/"
4
- html = '''
10
+ r = requests.get(url)
5
- <title>タイトル</title>
11
+ r.encoding = r.apparent_encoding
6
12
 
7
- <div class="abcde">
8
- <h2>果物</h2>
9
- <a href="URL">りんご</a>
13
+ soup = BeautifulSoup(r.text, "html.parser")
10
- <a href="URL">みかん</a>
14
+ elms = soup.select_one('h3:-soup-contains("「私に向いているかも!」を見つける職種図鑑") ~ ul:has(~ h3:-soup-contains("ここまで知っておけば失敗しない!応募前におさえるべき「内定後のやることリスト」"))')
11
- <a href="URL">ぶどう</a>
12
15
 
13
- <h2>野菜</h2>
14
- <a href="URL_carrot">にんじん</a>
15
- <a href="URL_cabbage">キャベツ</a>
16
- <a href="URL_tomato">トマト</a>
17
-
18
- <h2>飲み物</h2>
19
- <a href="URL">お茶</a>
20
- <a href="URL">お水</a>
21
- <a href="URL">牛乳</a>
22
- </div>
23
- '''
16
+ a = elms.select('a')
24
-
25
- soup = BeautifulSoup(html, 'html.parser')
26
- elms = soup.select('h2:-soup-contains("野菜") ~ a:has(~ h2:-soup-contains("飲み物"))')
27
-
28
17
  url, anchor = [], []
29
- for e in elms:
18
+ for e in a:
30
19
  url.append(e['href'])
31
20
  anchor.append(e.text)
32
21
 
33
22
  print(f'{url = }')
34
23
  print(f'{anchor = }')
24
+ ```
35
25
 
36
- #
37
- url = ['URL_carrot', 'URL_cabbage', 'URL_tomato']
38
- anchor = ['にんじん', 'キャベツ', 'トマト']
39
- ```