Pythonライブラリ pyquery 完全ガイド:WebスクレイピングをjQueryライクに

,
] # 子要素を取得 (children) – セレクタでフィルタ可能 ul_children = d(‘ul.items’).children() print(f”ul.itemsの子要素: {ul_children}”) # li要素がリストで返る important_child = d(‘ul.items’).children(‘.important’) print(f”ul.itemsの子要素(.important): {important_child}”) # 次の兄弟要素を取得 (next) – セレクタでフィルタ可能 next_sibling = d(‘li.item-1’).next() print(f”li.item-1の次の兄弟要素: {next_sibling}”) # [
  • ] # next_important = d(‘li.item-1’).next(‘.important’) # セレクタ指定も可 # 前の兄弟要素を取得 (prev) – セレクタでフィルタ可能 prev_sibling = d(‘li.item-2’).prev() print(f”li.item-2の前の兄弟要素: {prev_sibling}”) # [
  • ] # すべての次の兄弟要素を取得 (nextAll) – セレクタでフィルタ可能 next_all_siblings = d(‘li.item-1’).nextAll() # .next_all() も可 print(f”li.item-1の後の全兄弟要素: {next_all_siblings}”) # [
  • ,
  • ] # すべての前の兄弟要素を取得 (prevAll) – セレクタでフィルタ可能 prev_all_siblings = d(‘li.item-3’).prevAll() # .prev_all() も可 print(f”li.item-3の前の全兄弟要素: {prev_all_siblings}”) # [
  • ,
  • ] # すべての兄弟要素を取得 (siblings) – セレクタでフィルタ可能 all_siblings = d(‘li.item-2’).siblings() print(f”li.item-2の全兄弟要素: {all_siblings}”) # [
  • ,
  • ] item_1_sibling = d(‘li.item-2’).siblings(‘.item-1’) print(f”li.item-2の兄弟要素(.item-1): {item_1_sibling}”) # 指定した要素内で子孫要素を検索 (find) link_in_main = d(‘#main’).find(‘a’) print(f”#main内のa要素: {link_in_main}”) # [] p_in_sub_section = d(‘#main’).find(‘.sub-section p’) print(f”#main .sub-section 内のp要素: {p_in_sub_section}”) # 要素をフィルタリング (filter) important_lis = d(‘li’).filter(‘.important’) print(f”.importantクラスを持つli要素: {important_lis}”) # [
  • ] # 関数を使ってフィルタリングも可能 #lis_with_long_text = d(‘li’).filter(lambda i, el: len(pq(el).text()) > 5) #print(f”テキストが5文字より長いli要素: {lis_with_long_text}”) # 要素を除外 (not) non_important_lis = d(‘li’).not_(‘.important’) # .not_() を使う (notはPythonの予約語) print(f”.importantクラスを持たないli要素: {non_important_lis}”) # [
  • ,
  • ]
  • コメントを残す

    メールアドレスが公開されることはありません。 が付いている欄は必須項目です